﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Smallerp.Contracts;
using System.Data;
using SmallERP.DAL;
using System.ServiceModel;
using System.Data.OleDb;
using SmallERP.COM;
using Smallerp.Contracts.DataContracts;
using System.Drawing;

namespace Smallerp.Services
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
    public class OperateDBServer : IOperateDB
    {
        //public DataTable QueryDataTable(string inSql)
        //{
        //    return AccessHelper.dataTable(inSql);
        //}
        //public int ExecuteNonQuery(string inSql)
        //{
        //    return AccessHelper.ExecuteNonQuery(inSql);
        //}
        //public object ExecuteScalar(string inSql)
        //{
        //    return AccessHelper.ExecuteScalar(inSql);
        //}


        #region IOperateDB 成员

        DataTable IOperateDB.QueryDataTable(string inSql)
        {
            return AccessHelper.dataTable(inSql);
        }

        int IOperateDB.ExecuteNonQuery(string sqlstr)
        {
            return AccessHelper.ExecuteNonQuery(sqlstr);
        }

        object IOperateDB.ExecuteScalar(string sqlstr)
        {
            return AccessHelper.ExecuteScalar(sqlstr);
        }

        string istDota = "','";
        /// <summary>
        /// 插入订单信息
        /// </summary>
        /// <param name="inView"></param>
        /// <returns></returns>
        int IOperateDB.AddOrderToDB(Smallerp.Contracts.DataContracts.OrderViewDCT inView)
        {
            int rtnNum = 0;

            //string orderQuerySql = "select * from orderinfo where OrderName='" + inView.OrderName + "' and OrilOrderPath='" + inView.OrilOrderPath + "'";
            //DataTable orderTable = SmallERP.DAL.AccessHelper.dataTable(orderQuerySql);
            //if (orderTable.Rows.Count > 0)
            //{
            //    rtnNum = -1;
            //}
            //else//重复
            //{
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                bool isSucess = true;
                int intNum = inView.ProductNum;
                while (intNum > 0)
                {
                    string OrderName = "";
                    if (inView.ProductNum > 1)
                    {
                        OrderName = inView.OrderName.ToString() + "(" + intNum + ")";
                    }
                    else
                    {
                        OrderName = inView.OrderName;
                    }
                    string insertOrderSql = "insert into orderinfo (OrderName,OrderPath,PaperFaceId,PaperTypeId,Priority,ProductNum,"
                                                      + " Remark,SameFlagOrderId,StartTime,CompleteTime,Status,OrilOrderPath,FatherFolder,GranddadFolder)"
                                                      + " values ('" + OrderName.Replace("'", "''") + istDota + inView.OrderPath.Replace("'", "''") + istDota + inView.PaperFace.PaperFaceId + istDota + inView.PaperTypeInfo.PaperTypeId + istDota + inView.Priority + istDota + inView.ProductNum
                                                      + istDota + inView.Remark + istDota + inView.SameFlagOrderId + istDota + DateTime.Now + istDota + DateTime.Now + istDota + (int)Status.OrderStatus.Doing + istDota + inView.OrilOrderPath + "','" + inView.FatherFolder + "','" + inView.GranddadFolder + "')";

                    int insertOrder = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertOrderSql, oleconn, tran);
                    string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "' order by orderproductid desc";
                    //string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "'";
                    var orderID = SmallERP.DAL.AccessHelper.ExecuteScalar(orderNewSql, oleconn, tran);
                    if (insertOrder == 0)
                    {
                        rtnNum = 0;

                    }
                    else
                    {
                        int PhotoNumInOrder = 1;
                        foreach (PhotoDCT photo in inView.PhotoS)
                        {
                            string photoRemark = "";
                            if (string.IsNullOrEmpty(photo.Remark))
                            {
                                photoRemark = "";
                            }
                            else
                            {
                                photoRemark = photo.Remark.Replace("'", "''");
                            }
                            string insertPhotoSql = "insert into photoinfo(Height,IsClearBox,IsReback,PhotoName,OrderProductId,PicPath,PixHeight,PixWidth,PicOripath"
                                                                           + ",PrinterId,Remark,SameFlagPhotoId,Status,TotalNum,Width,userid,DPI,ColorType,PaperFaceId,PaperTypeId,photoOrderNum)"

                                                                 + "values('" + photo.Height + istDota + 0 + istDota + 0 + istDota + photo.PhotoName.Replace("'", "''") + istDota + orderID + istDota + photo.PicPath.Replace("'", "''") + istDota + photo.PixHeight + istDota + photo.PixWidth + istDota + photo.PicOripath.Replace("'", "''") + istDota
                                                                 + photo.PrinterId + istDota + photoRemark.Replace("'", "''") + istDota + photo.SameFlagPhotoId + istDota + (int)Status.PhotoStatus.WaitPB + istDota + photo.TotalNum + istDota + photo.Width + "',0," + photo.DPI + "," + photo.ColorType + "," + photo.PaperFaceId + "," + photo.PaperTypeID + "," + PhotoNumInOrder + ")";
                            int InsertPhoto = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertPhotoSql, oleconn, tran);
                            PhotoNumInOrder++;
                            if (InsertPhoto == 0)
                            {
                                isSucess = false;
                                break;

                            }
                            else
                            {
                                continue;
                            }
                        }
                        if (!isSucess)
                        {
                            break;
                        }
                    }


                    intNum--;
                }
                if (!isSucess)
                {
                    tran.Rollback();
                    rtnNum = 0;
                }
                else
                {
                    tran.Commit();
                    rtnNum = 1;
                }

                //}



            }
            AccessHelper.CloseMyConnection(oleconn);
            return rtnNum;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inView"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        int IOperateDB.AddOrderToDB2(Smallerp.Contracts.DataContracts.OrderViewDCT inView, int inModel)
        {
            int rtnNum = 0;

            //string orderQuerySql = "select * from orderinfo where OrderName='" + inView.OrderName + "' and OrilOrderPath='" + inView.OrilOrderPath + "'";
            //DataTable orderTable = SmallERP.DAL.AccessHelper.dataTable(orderQuerySql);
            //if (orderTable.Rows.Count > 0)
            //{
            //    rtnNum = -1;
            //}
            //else//重复
            //{
            int waitPinPhotoStatus=(int)SmallERP.COM.Status.PhotoStatus.WaitPB;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                if (inModel == 1)
                {
                    string upOrderPri = "Update orderinfo set Priority=1 where orderproductid in ( select  distinct orderproductid from photoinfo where status=" + waitPinPhotoStatus+")";
                    //string upPhotoPri = "Update photoinfo set Priority=1 where status=" +waitPinPhotoStatus;
                    AccessHelper.excuteSql(upOrderPri);
                   // AccessHelper.excuteSql(upPhotoPri);
                }
                bool isSucess = true;
                int intNum = inView.ProductNum;
                while (intNum > 0)
                {
                    string OrderName = "";
                    if (inView.ProductNum > 1)
                    {
                        OrderName = inView.OrderName.ToString() + "(" + intNum + ")";
                    }
                    else
                    {
                        OrderName = inView.OrderName;
                    }
                    string insertOrderSql = "insert into orderinfo (OrderName,OrderPath,PaperFaceId,PaperTypeId,Priority,ProductNum,"
                                                      + " Remark,SameFlagOrderId,StartTime,CompleteTime,Status,OrilOrderPath,FatherFolder,GranddadFolder)"
                                                      + " values ('" + OrderName.Replace("'", "''") + istDota + inView.OrderPath.Replace("'", "''") + istDota + inView.PaperFace.PaperFaceId + istDota + inView.PaperTypeInfo.PaperTypeId + istDota + inView.Priority + istDota + inView.ProductNum
                                                      + istDota + inView.Remark + istDota + inView.SameFlagOrderId + istDota + DateTime.Now + istDota + DateTime.Now + istDota + (int)Status.OrderStatus.Doing + istDota + inView.OrilOrderPath + "','" + inView.FatherFolder + "','" + inView.GranddadFolder + "')";

                    int insertOrder = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertOrderSql, oleconn, tran);
                    string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "' order by orderproductid desc";
                    //string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "'";
                    var orderID = SmallERP.DAL.AccessHelper.ExecuteScalar(orderNewSql, oleconn, tran);
                    if (insertOrder == 0)
                    {
                        rtnNum = 0;

                    }
                    else
                    {
                        int PhotoNumInOrder = 1;
                        foreach (PhotoDCT photo in inView.PhotoS)
                        {
                            string photoRemark = "";
                            if (string.IsNullOrEmpty(photo.Remark))
                            {
                                photoRemark = "";
                            }
                            else
                            {
                                photoRemark = photo.Remark.Replace("'", "''");

                            }
                             int InsertPhoto=0;
                            for (int i = 0; i < photo.TotalNum; i++)
                            {
                                string insertPhotoSql = "insert into photoinfo(Height,IsClearBox,IsReback,PhotoName,OrderProductId,PicPath,PixHeight,PixWidth,PicOripath"
                                                                               + ",PrinterId,Remark,SameFlagPhotoId,Status,TotalNum,Width,userid,DPI,ColorType,PaperFaceId,PaperTypeId,photoOrderNum,DXFFilePath,DXFContent)"

                                                                     + "values('" + photo.Height + istDota + 0 + istDota + 0 + istDota + photo.PhotoName.Replace("'", "''") + istDota + orderID + istDota + photo.PicPath.Replace("'", "''") + istDota + photo.PixHeight + istDota + photo.PixWidth + istDota + photo.PicOripath.Replace("'", "''") + istDota
                                                                     + photo.PrinterId + istDota + photoRemark.Replace("'", "''") + istDota + photo.SameFlagPhotoId + istDota + (int)Status.PhotoStatus.WaitPB + istDota + photo.TotalNum + istDota + photo.Width + "',0," + photo.DPI + "," + photo.ColorType + "," + photo.PaperFaceId + "," + photo.PaperTypeID + "," + PhotoNumInOrder + ",'" + photo.DXFFilePath + "',@DXFContent)";
                                OleDbParameter[] parameters = new OleDbParameter[1];

                                parameters[0] = new OleDbParameter("@DXFContent", photo.DXFContent == null ? new Byte[1] : photo.DXFContent);
                                InsertPhoto = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertPhotoSql, oleconn, tran, parameters);
                                PhotoNumInOrder++;
                            }
                            if (InsertPhoto == 0)
                            {
                                isSucess = false;
                                break;

                            }
                            else
                            {
                                continue;
                            }
                        }
                        if (!isSucess)
                        {
                            break;
                        }
                    }


                    intNum--;
                }
                if (!isSucess)
                {
                    tran.Rollback();
                    rtnNum = 0;
                }
                else
                {
                    tran.Commit();
                    rtnNum = 1;
                }

                //}



            }
            AccessHelper.CloseMyConnection(oleconn);
            return rtnNum;
        }
        int IOperateDB.AddOrderToDB2MoveBefore(Smallerp.Contracts.DataContracts.OrderViewDCT inView, int inModel)
        {
            int rtnNum = 0;

            //string orderQuerySql = "select * from orderinfo where OrderName='" + inView.OrderName + "' and OrilOrderPath='" + inView.OrilOrderPath + "'";
            //DataTable orderTable = SmallERP.DAL.AccessHelper.dataTable(orderQuerySql);
            //if (orderTable.Rows.Count > 0)
            //{
            //    rtnNum = -1;
            //}
            //else//重复
            //{
            int waiMoveOrderStatus = (int)SmallERP.COM.Status.OrderStatus.WaitMove;
            int waitMovePhotoStatus = (int)SmallERP.COM.Status.PhotoStatus.WaitMove;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                if (inModel == 1)
                {
                    string upOrderPri = "Update orderinfo set Priority=1 where orderproductid in ( select  distinct orderproductid from photoinfo where status=" + waitMovePhotoStatus + ")";
                    //string upPhotoPri = "Update photoinfo set Priority=1 where status=" +waitPinPhotoStatus;
                    AccessHelper.excuteSql(upOrderPri);
                    // AccessHelper.excuteSql(upPhotoPri);
                }
                bool isSucess = true;
                int intNum = inView.ProductNum;
                while (intNum > 0)
                {
                    string OrderName = "";
                    if (inView.ProductNum > 1)
                    {
                        OrderName = inView.OrderName.ToString() + "(" + intNum + ")";
                    }
                    else
                    {
                        OrderName = inView.OrderName;
                    }
                    string insertOrderSql = "insert into orderinfo (OrderName,OrderPath,PaperFaceId,PaperTypeId,Priority,ProductNum,"
                                                      + " Remark,SameFlagOrderId,StartTime,CompleteTime,Status,OrilOrderPath,FatherFolder,GranddadFolder)"
                                                      + " values ('" + OrderName.Replace("'", "''") + istDota + inView.OrderPath.Replace("'", "''") + istDota + inView.PaperFace.PaperFaceId + istDota + inView.PaperTypeInfo.PaperTypeId + istDota + inView.Priority + istDota + inView.ProductNum
                                                      + istDota + inView.Remark + istDota + inView.SameFlagOrderId + istDota + DateTime.Now + istDota + DateTime.Now + istDota + (int)Status.OrderStatus.WaitMove + istDota + inView.OrilOrderPath + "','" + inView.FatherFolder + "','" + inView.GranddadFolder + "')";

                    int insertOrder = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertOrderSql, oleconn, tran);
                    string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "' order by orderproductid desc";
                    //string orderNewSql = "select orderproductid from orderinfo where OrderName='" + OrderName + "'";
                    var orderID = SmallERP.DAL.AccessHelper.ExecuteScalar(orderNewSql, oleconn, tran);
                    if (insertOrder == 0)
                    {
                        rtnNum = 0;

                    }
                    else
                    {
                        int PhotoNumInOrder = 1;
                        foreach (PhotoDCT photo in inView.PhotoS)
                        {
                            string photoRemark = "";
                            if (string.IsNullOrEmpty(photo.Remark))
                            {
                                photoRemark = "";
                            }
                            else
                            {
                                photoRemark = photo.Remark.Replace("'", "''");

                            }
                            int InsertPhoto = 0;
                            for (int i = 0; i < photo.TotalNum; i++)
                            {
                                string insertPhotoSql = "insert into photoinfo(Height,IsClearBox,IsReback,PhotoName,OrderProductId,PicPath,PixHeight,PixWidth,PicOripath"
                                                                               + ",PrinterId,Remark,SameFlagPhotoId,Status,TotalNum,Width,userid,DPI,ColorType,PaperFaceId,PaperTypeId,photoOrderNum,DXFFilePath,DXFContent)"

                                                                     + "values('" + photo.Height + istDota + 0 + istDota + 0 + istDota + photo.PhotoName.Replace("'", "''") + istDota + orderID + istDota + photo.PicPath.Replace("'", "''") + istDota + photo.PixHeight + istDota + photo.PixWidth + istDota + photo.PicOripath.Replace("'", "''") + istDota
                                                                     + photo.PrinterId + istDota + photoRemark.Replace("'", "''") + istDota + photo.SameFlagPhotoId + istDota + (int)Status.PhotoStatus.WaitMove + istDota + photo.TotalNum + istDota + photo.Width + "',0," + photo.DPI + "," + photo.ColorType + "," + photo.PaperFaceId + "," + photo.PaperTypeID + "," + PhotoNumInOrder + "'" + photo.DXFFilePath + "',@DXFContent)";
                                OleDbParameter[] parameters=new OleDbParameter[1];
                                parameters[0] = new OleDbParameter("@DXFContent", photo.DXFContent);
                                InsertPhoto = SmallERP.DAL.AccessHelper.ExecuteNonQuery(insertPhotoSql, oleconn, tran, parameters);
                                 //string upDxfContent=up
                                PhotoNumInOrder++;
                            }
                            if (InsertPhoto == 0)
                            {
                                isSucess = false;
                                break;

                            }
                            else
                            {
                                continue;
                            }
                        }
                        if (!isSucess)
                        {
                            break;
                        }
                    }


                    intNum--;
                }
                if (!isSucess)
                {
                    tran.Rollback();
                    rtnNum = 0;
                }
                else
                {
                    tran.Commit();
                    rtnNum = 1;
                }

                //}



            }
            AccessHelper.CloseMyConnection(oleconn);
            return rtnNum;
        }

        public bool AddDXFContent(int orderid, string dxfPath, byte[] dexContent)
        {
            bool rtBool = false;
            using (OleDbConnection oleconn = AccessHelper.OpenMyConnection())
            {
                string picPathSql = "update orderinfo set dxfContent=@dxfContent,DXFFilePath =@dxfPath  where  OrderProductId=" + orderid;
                OleDbParameter[] parameters= new OleDbParameter[2];
                parameters[0] = new OleDbParameter("@dxfContent", dexContent);
                parameters[1] = new OleDbParameter("@dxfPath", dxfPath);
                int queryNum = (AccessHelper.ExecuteNonQuery(picPathSql, parameters));
                if (queryNum > 0)
                {
                    rtBool = true;
                }
                else
                {
                    rtBool = false;
                }
                return rtBool;
            }
        }

        public bool AddPhotoDXFContent(int photoId, string dxfpath, byte[] dexContent)
        {
            bool rtBool = false;
            using (OleDbConnection oleconn = AccessHelper.OpenMyConnection())
            {
                string picPathSql = "update  photoinfo set dxfContent=@dxfContent,DXFFilePath =@dxfPath  where  photoid=" + photoId;
                OleDbParameter[] parameters = new OleDbParameter[2];
                parameters[0] = new OleDbParameter("@dxfContent", dexContent);
                parameters[1] = new OleDbParameter("@dxfPath", dxfpath);
                int queryNum = (AccessHelper.ExecuteNonQuery(picPathSql, parameters));
                if (queryNum > 0)
                {
                    rtBool = true;
                }
                else
                {
                    rtBool = false;
                }
                return rtBool;
            }
        }

        //public bool AddDXFContent(int orderid, string dxfContent)
        //{
        //    bool rtBool = false;
        //    using (OleDbConnection oleconn = AccessHelper.OpenMyConnection())
        //    {
        //        string picPathSql = "update orderinfo set dxfContent='' where  OrderProductId=" + orderid;
        //        int  queryNum = (AccessHelper.ExecuteNonQuery(picPathSql));
        //        if (queryNum > 0)
        //        {
        //            rtBool = true;
        //        }
        //        else
        //        {
        //            rtBool = false;
        //        }
        //        return rtBool;
        //    }
           


        //}

        /// <summary>
        /// 检查大板
        /// </summary>
        /// <param name="inList"></param>
        /// <returns></returns>
        private bool CheckPhoto(List<PhotoInfo_PBDCT> inList)
        {
            int iCount = inList.Count;
            for (int i = 0; i < iCount; i++)
            {
                for (int j = i + 1; j < iCount; j++)
                {
                    //i j位置进行判断矩形是否重合
                    // return true;
                    PhotoInfo_PBDCT P1 = inList[i];
                    PhotoInfo_PBDCT P2 = inList[j];

                    //两个矩形框的边的一半
                    decimal halfP1W = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactHeigth / 2 : P1.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP2W = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactHeigth / 2 : P2.Photo_Base_Info.PixFactWidth / 2;
                    decimal halfP1H = (P1.IsWhirl == true) ? P1.Photo_Base_Info.PixFactWidth / 2 : P1.Photo_Base_Info.PixFactHeigth / 2;
                    decimal halfP2H = (P2.IsWhirl == true) ? P2.Photo_Base_Info.PixFactWidth / 2 : P2.Photo_Base_Info.PixFactHeigth / 2;

                    //两个矩形框的中心位置
                    decimal c1x = P1.Location.X + halfP1W;
                    decimal c1y = P1.Location.Y + halfP1H;
                    decimal c2x = P2.Location.X + halfP2W;
                    decimal c2y = P2.Location.Y + halfP2H;
                    //横向判断
                    if (Math.Abs(c1x - c2x) >= halfP1W + halfP2W || Math.Abs(c1y - c2y) >= halfP1H + halfP2H)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }


                }
            }
            return false;
        }
        /// <summary>
        /// 创建大板信息
        /// </summary>
        /// <param name="PicList"></param>
        /// <param name="tb_paperTemplate_Info"></param>
        /// <param name="printer_Info"></param>
        /// <param name="wasteRate"></param>
        /// <param name="realBoardLength"></param>
        /// <param name="isNeedAddNewTemplate"></param>
        /// <param name="BoardFolderPath"></param>
        /// <returns>返回版号</returns>
        public int CreateBoard(List<PhotoInfo_PBDCT> PicList, BoardTemplate_DCT tb_paperTemplate_Info, PrinterDCT printer_Info, float wasteRate, int realBoardLength, bool isNeedAddNewTemplate, string BoardFolderPath, int boardType=0)
        {
            //if (CheckPhoto(PicList))
            //{
            //    return -1;   
            //}
            int result = 0;//正常
            int MaxPriority = 0;//大板的加急级别

            int maxY = 0;//垂直方向自动居中     
            int disT = 0;//移动的距离
            int maxX = 0;//版长
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                int boardHeight = Convert.ToInt32(tb_paperTemplate_Info.Height * printer_Info.PDPI);
                string picPathSql = "select BigPicSavePath from SysSetting";
                string PicPath = Convert.ToString(AccessHelper.ExecuteScalar(picPathSql, oleconn, tran));
                string CreateTime = DateTime.Now.ToString();
                string insertBoard = "insert into board (CreateTime,DPI,Length,PaperTypeId,PaperFaceId,LastPrintTime,PrinterId,picPath,Height,Remark,Status,PrintNum,WasteRate,PrintPaperId,PrintPriority,IsClear,TemplateID,BoardProcudtType)"
                                   + " values ('" + CreateTime + istDota + printer_Info.PDPI + istDota + realBoardLength + istDota + tb_paperTemplate_Info.PaperTypeId + istDota + tb_paperTemplate_Info.PaperFaceId
                                   + istDota + CreateTime + istDota + printer_Info.PrinterID + istDota + " " + istDota + boardHeight + istDota + "生成数据成功" + istDota + (int)SmallERP.COM.Status.EnumBoardStatus.waitProduct
                                   + istDota + 0 + istDota + wasteRate + "',0," + PicList.Max(p => p.Priority) + ",0," + tb_paperTemplate_Info.TemplateId+","+boardType+")";
                int RtninsertBoard = AccessHelper.ExecuteNonQuery(insertBoard, oleconn, tran);
                int Boardid = Convert.ToInt32(AccessHelper.ExecuteScalar(@"select @@identity", oleconn, tran));

                //int Boardid = (int)AccessHelper.ExecuteScalar("select boardid from board where createtime=#" + CreateTime + "# order by createtime desc", oleconn, tran);
                result = Boardid;
                bool isSucess = true;
                if (printer_Info.IsMiddle)
                {
                    //向picmakeup表添加相关的信息
                    //if (isNeedAddNewTemplate)//只有手动拼板时才需要，全自拼板时不需要
                    //{
                    #region 计算垂直居中的距离
                    maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI)) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom) ? 30 : 0));
                    //int maxy = listResult.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI)));
                    //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.Photo_Base_Info.PixWidth : p.Photo_Base_Info.PixHeight));
                    
                    if (boardHeight > maxY)
                    {
                        disT = (boardHeight-30 - maxY) / 2;
                        if (disT < 0)
                        {
                            disT = 0;
                        }
                    }
                    #endregion
                    //}
                }
                else
                {
                    disT = 0;
                   // maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI)) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom) ? 30 : 0));
                    //int maxy = listResult.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI)));
                    //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.Photo_Base_Info.PixWidth : p.Photo_Base_Info.PixHeight));


                    //if (boardHeight > maxY)
                    //{
                    //    disT = (boardHeight - maxY);
                    //    if (disT < 0)
                    //    {
                    //        disT = 0;
                    //    }
                    //}
                }

                int photoid = PicList.OrderByDescending(p => p.PhotoId).FirstOrDefault().PhotoId;
                List<int> SucessPhotoid = new List<int>();
                foreach (var phg in PicList.GroupBy(p => p.OrderProductId))
                {
                    foreach (var ph in phg)
                    {
                        if (ph.Photo_Base_Info.IsClearBox)//清柜的自动将加急级别升为最高
                            MaxPriority = 11;
                        if (ph.Priority > MaxPriority)
                        {
                            MaxPriority = ph.Priority;
                        }

                        //piTemp = dataBase.photoInfo.FirstOrDefault(p => p.PhotoId == ph.PhotoId);
                        int waitStatus = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                        //string selectPhoto
                        string UpdatePhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic + " where photoid=" + ph.PhotoId + " and status=" + waitStatus;
                        int rtnUpph = AccessHelper.ExecuteNonQuery(UpdatePhoto, oleconn, tran);
                        if (rtnUpph == 0)
                        {
                            string photoSta = "select status from photoinfo where photoid=" + ph.PhotoId;
                            rtnUpph = (int)AccessHelper.ExecuteScalar(photoSta, oleconn, tran);
                        }
                        if (rtnUpph > 0)
                        {
                            string Y = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString();
                            string X = ph.Location.X.ToString();
                            string aaa = X;
                            //if (ph.PhotoId == photoid)
                            //{
                            //    X = InterFace.Function1(X).ToString();
                            //    int aa = Convert.ToInt32(InterFace.Function2(X));
                            //}
                            string insertPicMakeup = "insert INTO PicMakeUp(BoardId,BarCodeStatus,photoid,IsWhirl,X,Y,LABEL)"
                                                  + "values(" + Boardid + "," + (int)ph.BarCodeStatus + "," + ph.PhotoId + "," + Convert.ToInt32(ph.IsWhirl) + ",'" + X + "','" + Y + "','" + ph.PhotoId + "\\" + ph.OrderName.Replace("'", "''") + "\\" + ph.PhotoName.Replace("'", "''") + DateTime.Now.ToString() + "')";
                            int RtnPmu = AccessHelper.ExecuteNonQuery(insertPicMakeup, oleconn, tran);
                            if (RtnPmu == 0)
                            {
                                string upmakedSql = "select count(photoid) from PicMakeUp where photoid=" + ph.PhotoId + " and boardid=" + Boardid;
                                RtnPmu = (int)AccessHelper.ExecuteScalar(upmakedSql, oleconn, tran);
                            }
                            if (RtnPmu > 0)
                            {
                                //SucessPhotoid.Add(ph.PhotoId);

                                continue;

                            }
                            else
                            {
                                //string UpdateBackPhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitPB + " where photoid=" + ph.PhotoId;
                                //int rtnBackUpph = _OperateDb.ExecuteNonQuery(UpdateBackPhoto);
                                isSucess = false;
                                break;
                            }
                        }
                        else
                        {
                            isSucess = false;
                            break;
                        }
                    }
                    if (!isSucess)
                    {
                        break;
                    }
                    //检查产品是否完成拼版
                    //string checkPhoto = "select count(*) from photoinfo where orderproductid="+phg.Key;
                    //int leftPhoto=(int)AccessHelper.ExecuteScalar(checkPhoto, oleconn, tran);
                    //if (leftPhoto == 0)
                    //{
                    //    int ChangOrder = (int)AccessHelper.ExecuteScalar("update orderinfo set status='"++"'", oleconn, tran);
                    //}
                    //else
                    //{
                    //    continue;
                    //}
                }
                maxX = PicList.Max(p => p.Location.X + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI)));

                if (isSucess)
                {
                    //string QueryBoard = "select boardid from board where createtime='" + CreateTime + "'";
                    //string boardid = Convert.ToString(AccessHelper.ExecuteScalar(QueryBoard, tran));
                    double BoardL = (double)maxX / printer_Info.PDPI * 2.54;
                    double BoardW = Convert.ToDouble(tb_paperTemplate_Info.Height * 2.54);
                    //string path = BoardFolderPath + "\\" + Boardid + "@" + Convert.ToDateTime(CreateTime).ToString("yyyyMMdd") + "-" + tb_paperTemplate_Info.BoardNameRemark + "-" + "(" + BoardW.ToString("0.0") + "x" + BoardL.ToString("0.0") + "cm)" + ".jpg";
                    string path = BoardFolderPath + "\\" + Boardid + "@" + tb_paperTemplate_Info.BoardNameRemark + "-" + "(" + BoardL.ToString("0.0") + "cm)" + ".jpg";

                    string upBoard = "update board set picPath='" + path + "',PrintPriority=" + MaxPriority + " where boardid = " + result;
                    int upBoardRtn = AccessHelper.ExecuteNonQuery(upBoard, oleconn, tran);
                    if (upBoardRtn == 0)
                    {
                        result = -1;
                        tran.Rollback();
                    }
                    else
                    {
                        tran.Commit();
                    }
                }
                else
                {
                    result = -1;
                    tran.Rollback();
                }
            }
            AccessHelper.CloseMyConnection(oleconn);

            return result;
        }
        public int CombinBoard(List<PhotoInfo_PBDCT> PicList, int transX, int inNewLength, int InOldBoardid, PrinterDCT printer_Info, BoardTemplate_DCT tb_paperTemplate_Info)
        {
            int result = 0;//正常
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
               double BoardL = (double)inNewLength / printer_Info.PDPI * 2.54;
               double BoardW = Convert.ToDouble(tb_paperTemplate_Info.Height * 2.54);
               string newSizeStr = "(" + BoardW + "x" + BoardL + "cm)";
                   //string path = BoardFolderPath + "\\" + Boardid + "@" + Convert.ToDateTime(CreateTime).ToString("yyyyMMddHHmmss") + "-" + tb_paperTemplate_Info.BoardNameRemark + "-" + "(" + BoardW.ToString("0.0") + "x" + BoardL.ToString("0.0") + "cm)" + ".jpg";

                string oldBoardPathsql = "select picPath from board where boardid=" + InOldBoardid;
                string oldBoardPath = (string)AccessHelper.ExecuteScalar(oldBoardPathsql, oleconn, tran);
                int leftKuohao = oldBoardPath.IndexOf("(");
                int rirgtKuohao = oldBoardPath.IndexOf(")");
                string newBoardPath = "";
                newBoardPath = oldBoardPath.Substring(0, leftKuohao) + oldBoardPath.Substring(rirgtKuohao+1);
               newBoardPath = newBoardPath.Insert(leftKuohao, newSizeStr);
               string updateOldSQl = "update board set Length=" + inNewLength + ",picPath='" + newBoardPath + "' where boardid=" + InOldBoardid;

                int isUp = AccessHelper.ExecuteNonQuery(updateOldSQl, oleconn, tran);
                if (isUp < 0)
                {
                    result = -1;
                }
                else
                {

                    
                    int boardHeight = Convert.ToInt32(tb_paperTemplate_Info.Height * printer_Info.PDPI);
                    int maxY = 0;//垂直方向自动居中     
                    int disT = 0;//移动的距离
                    int maxX = 0;//版长

                    int MaxPriority = 0;//大板的加急级别
                    bool isSucess = true;
                    if (printer_Info.IsMiddle)
                    {
                        //向picmakeup表添加相关的信息
                        //if (isNeedAddNewTemplate)//只有手动拼板时才需要，全自拼板时不需要
                        //{
                        #region 计算垂直居中的距离
                        maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom) ? 30 : 0)));

                        if (boardHeight > maxY)
                        {
                            disT = (boardHeight-30 - maxY) / 2;
                            if (disT < 0)
                            {
                                disT = 0;
                            }
                        }
                        #endregion
                        //}
                    }
                    else
                    {
                        maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI)) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom) ? 30 : 0));
                        //int maxy = listResult.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI)));
                        //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.Photo_Base_Info.PixWidth : p.Photo_Base_Info.PixHeight));


                        if (boardHeight > maxY)
                        {
                            disT = (boardHeight-30 - maxY);
                            if (disT < 0)
                            {
                                disT = 0;
                            }
                        }
                    }
                    foreach (var phg in PicList.GroupBy(p => p.OrderProductId))
                    {
                        foreach (var ph in phg)
                        {
                            if (ph.Photo_Base_Info.IsClearBox)//清柜的自动将加急级别升为最高
                                MaxPriority = 11;
                            if (ph.Priority > MaxPriority)
                            {
                                MaxPriority = ph.Priority;
                            }

                            //piTemp = dataBase.photoInfo.FirstOrDefault(p => p.PhotoId == ph.PhotoId);
                            int waitStatus = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                            //string selectPhoto
                            string UpdatePhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic + " where photoid=" + ph.PhotoId + " and status=" + waitStatus;
                            int rtnUpph = AccessHelper.ExecuteNonQuery(UpdatePhoto, oleconn, tran);
                            if (rtnUpph == 0)
                            {
                                string photoSta = "select status from photoinfo where photoid=" + ph.PhotoId;
                                rtnUpph = (int)AccessHelper.ExecuteScalar(photoSta, oleconn, tran);
                            }
                            if (rtnUpph > 0)
                            {
                                string Y = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString();
                                string X = ph.Location.X.ToString();
                                string aaa = X;
                                //if (ph.PhotoId == photoid)
                                //{
                                //    X = InterFace.Function1(X).ToString();
                                //    int aa = Convert.ToInt32(InterFace.Function2(X));
                                //}
                                string insertPicMakeup = "insert INTO PicMakeUp(BoardId,BarCodeStatus,photoid,IsWhirl,X,Y,LABEL)"
                                                      + "values(" + InOldBoardid + "," + (int)ph.BarCodeStatus + "," + ph.PhotoId + "," + Convert.ToInt32(ph.IsWhirl) + ",'" + X + "','" + Y + "','" + ph.PhotoId + "\\" + ph.OrderName.Replace("'", "''") + "\\" + ph.PhotoName.Replace("'", "''") + DateTime.Now.ToString() + "')";
                                int RtnPmu = AccessHelper.ExecuteNonQuery(insertPicMakeup, oleconn, tran);
                                if (RtnPmu == 0)
                                {
                                    string upmakedSql = "select count(photoid) from PicMakeUp where photoid=" + ph.PhotoId + " and boardid=" + InOldBoardid;
                                    RtnPmu = (int)AccessHelper.ExecuteScalar(upmakedSql, oleconn, tran);
                                }
                                if (RtnPmu > 0)
                                {
                                    //SucessPhotoid.Add(ph.PhotoId);

                                    continue;

                                }
                                else
                                {
                                    //string UpdateBackPhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitPB + " where photoid=" + ph.PhotoId;
                                    //int rtnBackUpph = _OperateDb.ExecuteNonQuery(UpdateBackPhoto);
                                    isSucess = false;
                                    break;
                                }
                            }
                            else
                            {

                                isSucess = false;
                                break;
                            }
                        }
                        if (!isSucess)
                        {
                            break;
                        }

                    }
                    if (isSucess)
                    {
                        tran.Commit();
                        result = 0;
                    }
                    else
                    {
                        tran.Rollback();
                        result = -1;
                    }
                }
            }
            return result;

        }
        /// <summary>
        /// 创建大板信息
        /// </summary>
        /// <param name="PicList"></param>
        /// <param name="tb_paperTemplate_Info"></param>
        /// <param name="printer_Info"></param>
        /// <param name="wasteRate"></param>
        /// <param name="realBoardLength"></param>
        /// <param name="isNeedAddNewTemplate"></param>
        /// <param name="BoardFolderPath"></param>
        /// <param name="IsSure"></param>
        /// <returns>返回版号</returns>
        public int CreateBoard2(List<PhotoInfo_PBDCT> PicList, BoardTemplate_DCT tb_paperTemplate_Info, PrinterDCT printer_Info, float wasteRate, int realBoardLength, bool isNeedAddNewTemplate, string BoardFolderPath, bool isSure)
        {
            //if (CheckPhoto(PicList))
            //{
            //    return -1;
            //}
            int result = 0;//正常
            int MaxPriority = 0;//大板的加急级别

            int maxY = 0;//垂直方向自动居中     
            int disT = 0;//移动的距离
            int maxX = 0;//版长
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                int boardHeight = Convert.ToInt32(tb_paperTemplate_Info.Height * printer_Info.PDPI);

                int boardStatus = isSure ? (int)SmallERP.COM.Status.EnumBoardStatus.waitProduct : (int)SmallERP.COM.Status.EnumBoardStatus.WaitSure;
                string picPathSql = "select BigPicSavePath from SysSetting";
                string PicPath = Convert.ToString(AccessHelper.ExecuteScalar(picPathSql, oleconn, tran));
                string CreateTime = DateTime.Now.ToString();
                string insertBoard = "insert into board (CreateTime,DPI,Length,PaperTypeId,PaperFaceId,LastPrintTime,PrinterId,picPath,Height,Remark,Status,PrintNum,WasteRate,PrintPaperId,PrintPriority,IsClear,TemplateID)"
                                   + " values ('" + CreateTime + istDota + printer_Info.PDPI + istDota + realBoardLength + istDota + tb_paperTemplate_Info.PaperTypeId + istDota + tb_paperTemplate_Info.PaperFaceId
                                   + istDota + CreateTime + istDota + printer_Info.PrinterID + istDota + " " + istDota + boardHeight + istDota + "生成数据成功" + istDota + boardStatus
                                   + istDota + 0 + istDota + wasteRate + "',0," + PicList.Max(p => p.Priority) + ",0," + tb_paperTemplate_Info.TemplateId+ ")";
                int RtninsertBoard = AccessHelper.ExecuteNonQuery(insertBoard, oleconn, tran);
                int Boardid = Convert.ToInt32(AccessHelper.ExecuteScalar(@"select @@identity", oleconn, tran));
                //int Boardid = (int)AccessHelper.ExecuteScalar("select boardid from board where createtime=#" + CreateTime + "# order by createtime desc", oleconn, tran);
                result = Boardid;
                bool isSucess = true;
                if (printer_Info.IsMiddle)
                {
                    //向picmakeup表添加相关的信息
                    //if (isNeedAddNewTemplate)//只有手动拼板时才需要，全自拼板时不需要
                    //{
                    #region 计算垂直居中的距离
                    maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI)));
                                       
                    if (boardHeight > maxY)
                    {
                        disT = (boardHeight-30 - maxY) / 2;
                        if (disT < 0)
                        {
                            disT = 0;
                        }
                    }
                    #endregion
                    //}
                }
                else
                {
                    //maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI)) + ((p.BarCodeStatus == SmallERP.COM.Status.PhotoBarCodeStatus.TopOrBottom) ? 30 : 0));
                    //int maxy = listResult.Max(p => p.Location.Y + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * DataTransfer.CurPrinerInfo.PDPI)));
                    maxY = PicList.Max(p => p.Location.Y + (p.IsWhirl ? p.Photo_Base_Info.PixWidth : p.Photo_Base_Info.PixHeight));

                    disT = 0;
                    //if (boardHeight > maxY)
                    //{
                    //    disT = (boardHeight - maxY);
                    //    if (disT < 0)
                    //    {
                    //        disT = 0;
                    //    }
                    //}
                }

                int photoid = PicList.OrderByDescending(p => p.PhotoId).FirstOrDefault().PhotoId;
                List<int> SucessPhotoid = new List<int>();
                foreach (var phg in PicList.GroupBy(p => p.OrderProductId))
                {
                    foreach (var ph in phg)
                    {
                        if (ph.Photo_Base_Info.IsClearBox)//清柜的自动将加急级别升为最高
                            MaxPriority = 11;
                        if (ph.Priority > MaxPriority)
                        {
                            MaxPriority = ph.Priority;
                        }

                        //piTemp = dataBase.photoInfo.FirstOrDefault(p => p.PhotoId == ph.PhotoId);
                        int waitStatus = (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                        //string selectPhoto
                        string UpdatePhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitProductBigPic + " where photoid=" + ph.PhotoId + " and status=" + waitStatus;
                        int rtnUpph = AccessHelper.ExecuteNonQuery(UpdatePhoto, oleconn, tran);
                        if (rtnUpph == 0)
                        {
                            string photoSta = "select status from photoinfo where photoid=" + ph.PhotoId;
                            rtnUpph = (int)AccessHelper.ExecuteScalar(photoSta, oleconn, tran);
                        }
                        if (rtnUpph > 0)
                        {
                            string Y = disT <= 0 ? ph.Location.Y.ToString() : (ph.Location.Y + disT).ToString();
                            string X = ph.Location.X.ToString();
                            string aaa = X;
                            //if (ph.PhotoId == photoid)
                            //{
                            //    X = InterFace.Function1(X).ToString();
                            //    int aa = Convert.ToInt32(InterFace.Function2(X));
                            //}
                            string insertPicMakeup = "insert INTO PicMakeUp(BoardId,BarCodeStatus,photoid,IsWhirl,X,Y,LABEL)"
                                                  + "values(" + Boardid + "," + (int)ph.BarCodeStatus + "," + ph.PhotoId + "," + Convert.ToInt32(ph.IsWhirl) + ",'" + X + "','" + Y + "','" + ph.PhotoId + "\\" + ph.OrderName.Replace("'", "''") + "\\" + ph.PhotoName.Replace("'", "''") + DateTime.Now.ToString() + "')";
                            int RtnPmu = AccessHelper.ExecuteNonQuery(insertPicMakeup, oleconn, tran);
                            if (RtnPmu == 0)
                            {
                                string upmakedSql = "select count(photoid) from PicMakeUp where photoid=" + ph.PhotoId + " and boardid=" + Boardid;
                                RtnPmu = (int)AccessHelper.ExecuteScalar(upmakedSql, oleconn, tran);
                            }
                            if (RtnPmu > 0)
                            {
                                //SucessPhotoid.Add(ph.PhotoId);

                                continue;

                            }
                            else
                            {
                                //string UpdateBackPhoto = "update photoinfo set status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitPB + " where photoid=" + ph.PhotoId;
                                //int rtnBackUpph = _OperateDb.ExecuteNonQuery(UpdateBackPhoto);
                                isSucess = false;
                                break;
                            }
                        }
                        else
                        {

                            isSucess = false;
                            break;
                        }
                    }
                    if (!isSucess)
                    {
                        break;
                    }
                    //检查产品是否完成拼版
                    //string checkPhoto = "select count(*) from photoinfo where orderproductid="+phg.Key;
                    //int leftPhoto=(int)AccessHelper.ExecuteScalar(checkPhoto, oleconn, tran);
                    //if (leftPhoto == 0)
                    //{
                    //    int ChangOrder = (int)AccessHelper.ExecuteScalar("update orderinfo set status='"++"'", oleconn, tran);
                    //}
                    //else
                    //{
                    //    continue;
                    //}
                }
                maxX = PicList.Max(p => p.Location.X + (p.IsWhirl ? Convert.ToInt32(((double)p.Photo_Base_Info.PixHeight) / p.Photo_Base_Info.DPI * printer_Info.PDPI) : Convert.ToInt32(((double)p.Photo_Base_Info.PixWidth) / p.Photo_Base_Info.DPI * printer_Info.PDPI)));

                if (isSucess)
                {
                    //string QueryBoard = "select boardid from board where createtime='" + CreateTime + "'";
                    //string boardid = Convert.ToString(AccessHelper.ExecuteScalar(QueryBoard, tran));
                    double BoardL = (double)maxX / printer_Info.PDPI * 2.54;
                    double BoardW = Convert.ToDouble(tb_paperTemplate_Info.Height * 2.54);
                    //string path = BoardFolderPath + "\\" + Boardid + "@" + Convert.ToDateTime(CreateTime).ToString("yyyyMMdd") + "-" + tb_paperTemplate_Info.BoardNameRemark + "-" + "(" + BoardW.ToString("0.0") + "x" + BoardL.ToString("0.0") + "cm)" + ".jpg";
                    string path = BoardFolderPath + "\\" + Boardid + "@" + tb_paperTemplate_Info.BoardNameRemark + "-" + "(" + BoardL.ToString("0.0") + "cm)" + ".jpg";

                    string upBoard = "update board set picPath='" + path + "',PrintPriority=" + MaxPriority + " where boardid =" + result;
                    int upBoardRtn = AccessHelper.ExecuteNonQuery(upBoard, oleconn, tran);
                    if (upBoardRtn == 0)
                    {
                        result = -1;
                        tran.Rollback();
                    }
                    else
                    {
                        tran.Commit();
                    }
                }
                else
                {
                    result = -1;
                    tran.Rollback();
                }
            }
            AccessHelper.CloseMyConnection(oleconn);

            return result;
        }
        /// <summary>
        /// 复制产品
        /// </summary>
        /// <param name="SelectOrderList"></param>
        /// <param name="AddNum"></param>
        /// <returns></returns>
        public int CopyOrder(List<OrderInfo_PBDCT> SelectOrderList, int AddNum)
        {
            int rtn = 0;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                if (SelectOrderList.Count > 0 && AddNum > 0)
                {

                    foreach (var oiInfo in SelectOrderList)
                    {
                        for (int i = 0; i < AddNum; i++)
                        {
                            string orderName = oiInfo.OrderName + "(" + (i + 1) + ")";
                            string insertOrder = "insert into orderinfo (CompleteTime,OrderName,OrderPath,PaperFaceId,PaperTypeId,Priority,ProductNum,Remark,Status,StartTime,SameFlagOrderId,OrilOrderPath)"
                                                 + "values('" + oiInfo.order_Base_Info.CompleteTime + istDota + orderName.Replace("'", "''") + istDota + oiInfo.order_Base_Info.OrderPath.Replace("'", "''") + istDota
                                                 + oiInfo.order_Base_Info.PaperFaceId + istDota
                                                 + oiInfo.order_Base_Info.PaperTypeId + istDota
                                                 + oiInfo.order_Base_Info.Priority + istDota + 1 + istDota
                                                 + oiInfo.order_Base_Info.Remark + istDota
                                                 + oiInfo.order_Base_Info.Status + istDota
                                                 + oiInfo.order_Base_Info.StartTime + istDota
                                                 + oiInfo.order_Base_Info.SameFlagOrderId + istDota
                                                 + oiInfo.order_Base_Info.OrilOrderPath.Replace("'", "''") + "')";
                            int insertOrderRtn = AccessHelper.ExecuteNonQuery(insertOrder, oleconn, tran);
                            int orderid = (int)AccessHelper.ExecuteScalar("select orderproductid from orderinfo where ordername='" + orderName + "'", oleconn, tran);

                            if (insertOrderRtn == 0)
                            {
                                goto bc;
                            }
                            else
                            {
                                foreach (var pi in oiInfo.PhotoList)
                                {
                                    string insertPhotoSQL = "insert into photoinfo (orderproductid,Height,IsClearBox,IsReback,Status,SameFlagPhotoId,PhotoName,PicPath,PixHeight,PixWidth,PrinterId,Remark,Width,TotalNum,userId,PicOripath,dpi,PaperFaceId,PaperTypeId,ColorType,DXFFilePath,DXFContent)"
                                    + "values(" + orderid + ",'" + pi.Photo_Base_Info.Height + istDota
                                    + Convert.ToInt32(pi.Photo_Base_Info.IsClearBox) + istDota
                                    + Convert.ToInt32(pi.Photo_Base_Info.IsReback) + istDota
                                    + (int)SmallERP.COM.Status.PhotoStatus.WaitPB + istDota
                                    + pi.Photo_Base_Info.SameFlagPhotoId + istDota
                                    + pi.Photo_Base_Info.PhotoName.Replace("'", "''") + istDota
                                    + pi.Photo_Base_Info.PicPath.Replace("'", "''") + istDota
                                    + pi.Photo_Base_Info.PixHeight + istDota
                                    + pi.Photo_Base_Info.PixWidth + istDota
                                    + pi.Photo_Base_Info.PrinterId + istDota
                                    + pi.Photo_Base_Info.Remark.Replace("'", "''") + istDota
                                    + pi.Photo_Base_Info.Width + istDota
                                    + pi.Photo_Base_Info.TotalNum + istDota
                                    + pi.Photo_Base_Info.UserId + istDota 
                                    + pi.Photo_Base_Info.PicOripath.Replace("'", "''") + "'," + pi.Photo_Base_Info.DPI + "," + pi.Photo_Base_Info.PaperFaceId + ","
                                    + pi.Photo_Base_Info.PaperTypeID + "," + pi.Photo_Base_Info.ColorType+",'"
                                    + pi.Photo_Base_Info.DXFFilePath + "',@DXFContent" 
                                    + ")";
                                    OleDbParameter[] para = new OleDbParameter[1];
                                    para[0] = new OleDbParameter("@DXFContent", pi.Photo_Base_Info.DXFContent == null ? new Byte[1] : pi.Photo_Base_Info.DXFContent);
                                    int insertPhotoRtn = AccessHelper.ExecuteNonQuery(insertPhotoSQL, oleconn, tran, para);
                                    if (insertPhotoRtn == 0)
                                    {
                                        rtn = 0;
                                        goto bc;
                                    }
                                    else
                                    {
                                        rtn = 1;
                                    }
                                }

                            }

                        }
                    }
                bc:
                    ;
                }
                if (rtn == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }

            }
            AccessHelper.CloseMyConnection(oleconn);
            return rtn;
        }

        public int CopyPhoto(List<PhotoInfo_PBDCT> SelectPhotoList, int AddNum)
        {
            int rtn = 0;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                foreach (var pi in SelectPhotoList)
                {
                    for (int i = 0; i < AddNum; i++)
                    {
                        string PhotoName = pi.PhotoName + "(" + (i + 1) + ")";
                        string insertPhotoSQL = "insert into photoinfo (orderproductid,Height,IsClearBox,IsReback,Status,SameFlagPhotoId,PhotoName,PicPath,PixHeight,PixWidth,PrinterId,Remark,Width,TotalNum,userId,PicOripath,dpi,ColorType,PaperFaceId,PaperTypeId,DXFFilePath,DXFContent)"
                                                + "values(" + pi.OrderProductId + ",'" + pi.Photo_Base_Info.Height +
                                                istDota
                                                + Convert.ToInt32(pi.Photo_Base_Info.IsClearBox) + istDota
                                                + Convert.ToInt32(pi.Photo_Base_Info.IsReback) + istDota
                                                + (int) SmallERP.COM.Status.PhotoStatus.WaitPB + istDota
                                                + pi.Photo_Base_Info.SameFlagPhotoId + istDota
                                                + pi.Photo_Base_Info.PhotoName.Replace("'", "''") + "" + istDota
                                                + pi.Photo_Base_Info.PicPath.Replace("'", "''") + istDota
                                                + pi.Photo_Base_Info.PixHeight + istDota
                                                + pi.Photo_Base_Info.PixWidth + istDota
                                                + pi.Photo_Base_Info.PrinterId + istDota
                                                + pi.Photo_Base_Info.Remark.Replace("'", "''") + istDota
                                                + pi.Photo_Base_Info.Width + istDota
                                                + pi.Photo_Base_Info.TotalNum + istDota
                                                + pi.Photo_Base_Info.UserId + istDota
                                                + pi.Photo_Base_Info.PicOripath.Replace("'", "''") + "',"
                                                + pi.Photo_Base_Info.DPI + "," + pi.Photo_Base_Info.ColorType + ","
                                                + pi.Photo_Base_Info.PaperFaceId + ","
                                                + pi.Photo_Base_Info.PaperTypeID + ",'"
                                                + pi.Photo_Base_Info.DXFFilePath + "', @DXFContent )";
                        
                        OleDbParameter[] para=new OleDbParameter[1];
                        para[0] = new OleDbParameter("@DXFContent", pi.Photo_Base_Info.DXFContent == null ? new Byte[1] : pi.Photo_Base_Info.DXFContent);
                        int insertPhotoRtn = AccessHelper.ExecuteNonQuery(insertPhotoSQL, oleconn, tran, para);
                        if (insertPhotoRtn == 0)
                        {
                            rtn = 0;
                            goto bc;
                        }
                        else
                        {
                            rtn = 1;
                        }
                    }
                }
            bc:
                {
                    ;
                }
                if (rtn == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }

            }
            AccessHelper.CloseMyConnection(oleconn);
            return rtn;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SelectPhotoList"></param>
        /// <returns></returns>
        public int DeletePhotos(List<PhotoInfo_PBDCT> SelectPhotoList)
        {
            int result = 0;
            OleDbConnection oleconn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleconn.BeginTransaction())
            {
                if (SelectPhotoList.Count > 0)
                {
                    foreach (var photoGroup in SelectPhotoList.GroupBy(p => p.OrderProductId))
                    {
                        foreach (PhotoInfo_PBDCT pit in photoGroup.ToList())
                        {
                            string delPhoto = "delete from photoinfo where photoid=" + pit.PhotoId;
                            int delPhotoRtn = AccessHelper.ExecuteNonQuery(delPhoto, oleconn, tran);
                            if (delPhotoRtn > 0)
                            {

                            }
                            else
                            {
                                goto breakPoint;

                            }
                        }
                        string CheckOrder = "select Count(photoid) from photoinfo where orderproductid=" + photoGroup.Key;
                        int chkInt = Convert.ToInt32(AccessHelper.ExecuteScalar(CheckOrder, oleconn, tran));
                        if (chkInt > 0)
                        {
                            //还有其他照片
                            result = 1;
                        }
                        else
                        {
                            string DelOrder = "delete  from orderinfo where orderproductid=" + photoGroup.Key;
                            int DelOrderRtn = AccessHelper.ExecuteNonQuery(DelOrder, oleconn, tran);
                            if (DelOrderRtn == 0)
                            {
                                result = 0;
                                goto breakPoint;
                            }
                            else
                            {
                                result = 1;
                            }
                        }

                    }
                }
            breakPoint: { ; }
                if (result == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }
            }
            AccessHelper.CloseMyConnection(oleconn);
            return result;
        }
        /// <summary>
        /// 删除产品
        /// </summary>
        /// <param name="SelectOrderList"></param>
        /// <returns></returns>
        public int DeleteOrders(List<OrderInfo_PBDCT> SelectOrderList)
        {
            int rtn = 0;
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                foreach (var oi in SelectOrderList)
                {
                    //string delOrderSql = "delete from orderinfo where orderproductid=" + oi.order_Base_Info.OrderProductId;
                    string delPhotoSql = "delete from photoinfo where orderproductid=" + oi.order_Base_Info.OrderProductId + " and status=" + (int)SmallERP.COM.Status.PhotoStatus.WaitPB;
                    int delOrderRtn = AccessHelper.ExecuteNonQuery(delPhotoSql, olecc, tran);
                    if (delOrderRtn == 0)
                    {
                        rtn = 0;
                        break;
                    }
                    else
                    {
                        rtn = 1;
                    }
                }
                if (rtn == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }
            }
            AccessHelper.CloseMyConnection(olecc);
            return rtn;

        }

        public int ModifyOrder(OrderInfo_PBDCT oiInfo)
        {

            int result = 0;
            if (oiInfo != null)
            {
                OleDbConnection olecc = AccessHelper.OpenMyConnection();
                using (OleDbTransaction tran = olecc.BeginTransaction())
                {
                    //修改产品信息
                    string UpdateOrderinSql = "update orderinfo set OrderName='" + oiInfo.order_Base_Info.OrderName + "',PaperFaceId=" + oiInfo.order_Base_Info.PaperFaceId + ",Priority=" + oiInfo.order_Base_Info.Priority + ",Remark='" + oiInfo.order_Base_Info.Remark + "' where orderproductid=" + oiInfo.order_Base_Info.OrderProductId;
                    int updateOrderrtn = AccessHelper.ExecuteNonQuery(UpdateOrderinSql, olecc, tran);


                    //修改照片的纸型纸面
                    string UpdatePhotoFaceAndTypeSql = "update photoinfo set PaperFaceId=" + oiInfo.order_Base_Info.PaperFaceId + " ,PaperTypeId=" + oiInfo.order_Base_Info.PaperTypeId + " where orderproductid=" + oiInfo.order_Base_Info.OrderProductId;
                    int UpdatePhotoFaceAndType = AccessHelper.ExecuteNonQuery(UpdatePhotoFaceAndTypeSql, olecc, tran);

                    //修改份数问题
                    for (int i = 0; i < oiInfo.ProductNum - 1; i++)
                    {
                        string orderName = oiInfo.OrderName + "(" + (i + 1) + ")";
                        string insertOrder = "insert into orderinfo (CompleteTime,OrderName,OrderPath,PaperFaceId,PaperTypeId,Priority,ProductNum,Remark,Status,StartTime,SameFlagOrderId,OrilOrderPath)"
                                             + "values('" + oiInfo.order_Base_Info.CompleteTime + istDota + oiInfo.order_Base_Info.OrderPath + istDota
                                             + oiInfo.order_Base_Info.PaperFaceId + istDota
                                             + oiInfo.order_Base_Info.PaperTypeId + istDota
                                             + oiInfo.order_Base_Info.Priority + istDota + 1
                                             + oiInfo.order_Base_Info.Remark + istDota
                                             + oiInfo.order_Base_Info.Status + istDota
                                             + oiInfo.order_Base_Info.StartTime + istDota
                                             + oiInfo.order_Base_Info.SameFlagOrderId
                                             + oiInfo.order_Base_Info.OrilOrderPath + "')";
                        int insertOrderRtn = AccessHelper.ExecuteNonQuery(insertOrder, olecc, tran);
                        int orderid = (int)AccessHelper.ExecuteScalar("select orderproductid from order where ordername='" + orderName + "'", olecc, tran);

                        if (insertOrderRtn == 0)
                        {
                            goto bc;
                        }
                        else
                        {
                            foreach (var pi in oiInfo.PhotoList)
                            {
                                string insertPhotoSQL = "insert into photoinfo (Height,IsClearBox,IsReback,Status,SameFlagPhotoId,PhotoName,PicPath,PixHeight,PixWidth,PrinterId,Remark,Width,TotalNum,userId,PicOripath,DPI,ColorType,PaperFaceId,PaperTypeId)"
                                + "values('" + pi.Photo_Base_Info.Height + istDota
                                + pi.Photo_Base_Info.IsClearBox + istDota
                                + pi.Photo_Base_Info.IsReback + istDota
                                + (int)SmallERP.COM.Status.PhotoStatus.WaitPB + istDota
                                + pi.Photo_Base_Info.SameFlagPhotoId + istDota
                                + pi.Photo_Base_Info.PhotoName + istDota
                                + pi.Photo_Base_Info.PicPath + istDota
                                + pi.Photo_Base_Info.PixHeight + istDota
                                + pi.Photo_Base_Info.PixWidth + istDota
                                + pi.Photo_Base_Info.PrinterId + istDota
                                + pi.Photo_Base_Info.Remark + istDota
                                + pi.Photo_Base_Info.Width + istDota
                                + pi.Photo_Base_Info.TotalNum + istDota
                                + pi.Photo_Base_Info.UserId + istDota + pi.Photo_Base_Info.PicOripath + "'," + pi.Photo_Base_Info.DPI + "," + pi.Photo_Base_Info.ColorType + "," + pi.Photo_Base_Info.PaperFaceId + "," + pi.Photo_Base_Info.PaperTypeID + ")";
                                int insertPhotoRtn = AccessHelper.ExecuteNonQuery(insertPhotoSQL, olecc, tran);
                                if (insertPhotoRtn == 0)
                                {
                                    result = 0;
                                    goto bc;
                                }
                                else
                                {
                                    result = 1;
                                }
                            }

                        }

                    }
                    string UpdateOrderInfo = "update orderinfo set PaperFaceId=" + oiInfo.order_Base_Info.PaperFaceId + ", PaperTypeId=" + oiInfo.order_Base_Info.PaperTypeId + ",Priority=" + oiInfo.order_Base_Info.Priority + ",remark='" + oiInfo.order_Base_Info.Remark + "' where orderproductid=" + oiInfo.order_Base_Info.OrderProductId;
                    int rtnOrder = AccessHelper.ExecuteNonQuery(UpdateOrderInfo, olecc, tran);
                    if (rtnOrder > 0)
                    {
                        result = 1;
                    }
                    else
                    {
                        result = 0;
                    }

                bc: { }
                    if (result == 0)
                    {
                        tran.Rollback();
                    }
                    else
                    {
                        tran.Commit();
                    }
                }
                AccessHelper.CloseMyConnection(olecc);
            }
            return result;
        }

        public List<PaperFaceDCT> GetAllPaperFace()
        {
            List<PaperFaceDCT> paperFaceList = new List<PaperFaceDCT>();
            DataTable dt = AccessHelper.dataTable("select * from PaperFace");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                PaperFaceDCT paperFace = new PaperFaceDCT();
                paperFace.PaperFaceId = Convert.ToInt32(row["PaperFaceId"]);
                paperFace.PaperFaceName = (row["PaperFaceName"]).ToString();
                paperFaceList.Add(paperFace);

            }

            return paperFaceList;
        }
        public List<PaperTypeDCT> GetAllPaperType()
        {
            List<PaperTypeDCT> list = new List<PaperTypeDCT>();
            DataTable dt = AccessHelper.dataTable("select * from PaperType");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                PaperTypeDCT paperFace = new PaperTypeDCT();
                paperFace.PaperTypeId = Convert.ToInt32(row["PaperTypeId"]);
                paperFace.PaperTypeName = (row["PaperTypeName"]).ToString();
                list.Add(paperFace);

            }
            return list;
        }

        public List<PrinterDCT> GetAllPrinters()
        {
            List<PrinterDCT> listPDCT = new List<PrinterDCT>();
            string QueryPrinter = "select * from printer ";
            DataTable Qtable = AccessHelper.dataTable(QueryPrinter);
            for (int i = 0; i < Qtable.Rows.Count; i++)
            {
                PrinterDCT printerInfo = new PrinterDCT();
                printerInfo.HotDirPath = Qtable.Rows[i]["hotDirPath"].ToString();
                printerInfo.IsTransverse = Convert.ToBoolean(Qtable.Rows[i]["IsTransverse"]);
                printerInfo.MonitorDirPath = Qtable.Rows[i]["MonitorDirPath"].ToString();
                printerInfo.PDes = Qtable.Rows[i]["PDes"].ToString(); ;
                printerInfo.PDPI = Convert.ToInt32(Qtable.Rows[i]["PDPI"]); ;
                printerInfo.PLength = Convert.ToDouble(Qtable.Rows[i]["PLength"]);
                printerInfo.PName = Qtable.Rows[i]["PName"].ToString();
                printerInfo.PrinterID = Convert.ToInt32(Qtable.Rows[i]["PrinterID"]);
                printerInfo.PWidth = Convert.ToInt32(Qtable.Rows[i]["PWidth"]);
                printerInfo.PrintStatus = Convert.ToInt32(Qtable.Rows[i]["PrintStatus"]);
                printerInfo.PBstatus = Convert.ToInt32(Qtable.Rows[i]["PBstatus"]);
                printerInfo.IsMiddle = Convert.ToBoolean(Qtable.Rows[i]["IsMiddle"]);
                printerInfo.PrinterType = Convert.ToInt32(Qtable.Rows[i]["PrinterType"]);
                listPDCT.Add(printerInfo);
            }

            return listPDCT;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="inBoardList"></param>
        /// <returns></returns>
        public int DeleteBoards(List<int> inBoardList)
        {
            int rtnval = 0;
            //AccessHelper();
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                foreach (int boardid in inBoardList)
                {
                    string UpdatePhoto = "update photoinfo set status=" + (int)Status.PhotoStatus.WaitPB + " where photoid in(select photoid from picmakeup where boardid =" + boardid + ")";
                    int upInt = AccessHelper.ExecuteNonQuery(UpdatePhoto, olecc, tran);
                    if (upInt > 0)
                    {
                        string delBoard = "delete  from board where boardid =" + boardid;
                        int delInt = AccessHelper.ExecuteNonQuery(delBoard, olecc, tran);
                        if (delInt == 0)
                        {
                            rtnval = 0;

                        }
                        else
                        {
                            rtnval = 1;
                        }
                    }
                    else
                    {
                        string delBoard = "delete  from board where boardid =" + boardid;
                        int delInt = AccessHelper.ExecuteNonQuery(delBoard, olecc, tran);
                        if (delInt == 0)
                        {
                            rtnval = 0;

                        }
                        else
                        {
                            rtnval = 1;
                        }
                    }

                }
                if (rtnval == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }
            }
            AccessHelper.CloseMyConnection(olecc);
            return rtnval;
        }
        /// <summary>
        /// 删除大板
        /// </summary>
        /// <param name="boardid"></param>
        /// <returns></returns>
        public int DeleteBoard(int boardid)
        {
            int rtnval = 0;
            //AccessHelper();
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                string UpdatePhoto = "update photoinfo set status=" + (int)Status.PhotoStatus.WaitPB + " where photoid in(select photoid from picmakeup where boardid =" + boardid + ")";
                int upInt = AccessHelper.ExecuteNonQuery(UpdatePhoto, olecc, tran);
                if (upInt > 0)
                {
                    string delBoard = "delete  from board where boardid =" + boardid;
                    int delInt = AccessHelper.ExecuteNonQuery(delBoard, olecc, tran);
                    if (delInt == 0)
                    {
                        rtnval = 0;

                    }
                    else
                    {
                        rtnval = 1;
                    }
                }
                else
                {
                    rtnval = 0;
                }
                if (rtnval == 0)
                {
                    tran.Rollback();
                }
                else
                {
                    tran.Commit();
                }
            }
            AccessHelper.CloseMyConnection(olecc);
            return rtnval;
        }
        /// <summary>
        /// 重新打印大板
        /// </summary>
        /// <param name="Boardid"></param>
        /// <returns></returns>
        public int RePrint(int Boardid, int paperid)
        {
            int retVal = 0;
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = olecc.BeginTransaction())
            {
                //string indertWaste="insert into PaperWasteRecords(Length,Width,PaperWasteTypeid,Remark,Status,CreateTime,PaperInfoid) select (photoInfo.Height * 2.54/100),(photoInfo.Width * 2.54) / 100),1,"+(int)Status.WasterPaperStatus.unSure+",'"+DateTime.Now+"',"+
                string QueryWasttypeid = "select Id from PaperWasteType where PaperOperationTypeName='" + "重新打印大板'";
                var rtn = AccessHelper.ExecuteScalar(QueryWasttypeid, olecc, tran);
                int Wasteid = 0;
                if (rtn != null)
                {
                    Wasteid = (int)rtn;
                }

                if (Wasteid == 0)
                {
                    AccessHelper.ExecuteNonQuery("insert into  PaperWasteType (PaperOperationTypeName) values('重新打印大板')", olecc, tran);
                }
                Wasteid = (int)AccessHelper.ExecuteScalar(QueryWasttypeid, olecc, tran);
                if (Wasteid == 0)
                {
                    retVal = 0;

                }
                else
                {
                    string QueryPhotoInfo = "select photoinfo.Height,photoinfo.Width,photoinfo.photoid,printerid from picmakeup,photoinfo where photoinfo.photoid=picmakeup.photoid and boardid=" + Boardid;
                    DataTable tablePhoto = AccessHelper.dataTable(QueryPhotoInfo, olecc, tran);
                    for (int i = 0; i < tablePhoto.Rows.Count; i++)
                    {
                        string insertWaste = " insert into PaperWasteRecords(Length,Width,PaperWasteTypeid,Remark,Status,CreateTime,PrintPaperId) values ("
                        + Convert.ToDouble(tablePhoto.Rows[i]["Height"]) * 2.54 / 100 + "," + Convert.ToDouble(tablePhoto.Rows[i]["Width"]) * 2.54 / 100 + "," + Wasteid + ",'重新打印大板'," + (int)SmallERP.COM.Status.WasterPaperStatus.unSure + ",'" + DateTime.Now + "'," + paperid + ")";
                        int insertwastetrn = AccessHelper.ExecuteNonQuery(insertWaste, olecc, tran);
                        if (insertwastetrn == 0)
                        {
                            retVal = 0;
                            break;
                        }
                        else
                        {
                            retVal = 1;

                        }
                    }
                }
                if (retVal == 1)
                {
                    //讲大板状态改为未打印
                    string updateBoard = "update board set status=" + (int)SmallERP.COM.Status.EnumBoardStatus.WaitingPrint + " where boardid=" + Boardid;
                    if (AccessHelper.ExecuteNonQuery(updateBoard) > 0)
                    {
                        tran.Commit();
                    }
                    else
                    {
                        tran.Rollback();

                    }

                }
                else
                {
                    tran.Rollback();

                }
            }
            AccessHelper.CloseMyConnection(olecc);
            return retVal;
        }
        public DataTable ChangerPaper(int printerid, int newPaperid)
        {
            DataTable rtnTable = null;
            bool IsSuccess = true;
            OleDbConnection olecc = AccessHelper.OpenMyConnection();
            using (var tran = olecc.BeginTransaction())
            {
                ///旧的标记成不在使用
                string UppaperOld = "update PaperInfo set Status=" + (int)Status.PaperInfoStatus.Used + " where status=" + (int)Status.PaperInfoStatus.Using + " and PrinterID=" + printerid;
                int OldVal = AccessHelper.ExecuteNonQuery(UppaperOld, olecc, tran);
                if (OldVal == 0)
                {
                    string UppaperNew = "update PaperInfo set Status=" + (int)Status.PaperInfoStatus.Using + ",printerid=" + printerid + " where PrintPaperId=" + newPaperid;
                    if (AccessHelper.ExecuteNonQuery(UppaperNew, olecc, tran) > 0)
                    {
                        rtnTable = AccessHelper.dataTable("select * from PaperInfo where PrintPaperId=" + newPaperid, olecc, tran);
                    }
                    else
                    {
                        IsSuccess = false;

                    }

                }
                else
                {
                    string UppaperNew = "update PaperInfo set Status=" + (int)Status.PaperInfoStatus.Using + ",PrinterID=" + printerid + " where PrintPaperId=" + newPaperid;
                    if (AccessHelper.ExecuteNonQuery(UppaperNew, olecc, tran) > 0)
                    {
                        rtnTable = AccessHelper.dataTable("select * from PaperInfo where PrintPaperId=" + newPaperid, olecc, tran);
                    }
                    else
                    {
                        IsSuccess = false;

                    }

                }
                if (IsSuccess)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                    rtnTable = null;
                }
            }

            return rtnTable;

        }

        /// <summary>
        /// 照片分配格子
        /// </summary>
        /// <param name="inPhotoID"ID</param>
        /// <param name="OutGridName">格子名字</param>
        /// <param name="outGridInfo_Grid">刷新界面的实体</param>
        /// <returns></returns>
        public int AssinGrid(int inPhotoID, out string OutGridName, out GridInfo_GridDCT outGridInfo_Grid, out int outGridID, int inSubAreaID)
        {

            OleDbConnection oleConn = AccessHelper.OpenMyConnection();
            try
            {
                using (OleDbTransaction tran = oleConn.BeginTransaction())
                {
                    string QueryPhoto = "select * from photoinfo where photoid=" + inPhotoID;
                    DataTable tablePhoto = AccessHelper.dataTable(QueryPhoto, oleConn, tran);
                    if (tablePhoto.Rows.Count == 0)
                    {
                        OutGridName = "";
                        outGridInfo_Grid = null;
                        outGridID = 0;
                        return -1;//找不到该照片
                    }
                    else
                    {
                        int photoStatus = (int)tablePhoto.Rows[0]["Status"];
                        if (photoStatus != (int)Status.PhotoStatus.InGrid && photoStatus != (int)Status.PhotoStatus.Printed && photoStatus != (int)Status.PhotoStatus.Producted)
                        {
                            OutGridName = "";
                            outGridInfo_Grid = null;
                            outGridID = 0;
                            return -2;//照片未打印
                        }
                        else
                        {
                            int orderproductid = (int)tablePhoto.Rows[0]["orderproductid"];
                            string QueryGrid = "select * from Grid where orderid=" + orderproductid;
                            DataTable tableGrid = AccessHelper.dataTable(QueryGrid, oleConn, tran);
                            if (tableGrid.Rows.Count > 0)//已经占用格子
                            {
                                int subAreasid = (int)tableGrid.Rows[0]["SubAreaId"];
                                int gridID = (int)tableGrid.Rows[0]["gridID"];
                                if (subAreasid != inSubAreaID)
                                {
                                    OutGridName = (string)AccessHelper.ExecuteScalar("select SubAreaName from GridSubArea where SubAreaID=" + inSubAreaID, oleConn, tran);
                                    outGridInfo_Grid = null;
                                    outGridID = 0;
                                    return -5;//不属于该分区
                                }
                                else
                                {
                                    OutGridName = (string)tableGrid.Rows[0]["GridName"];

                                    if (photoStatus != (int)Status.PhotoStatus.InGrid)
                                    {
                                        int UpdatePhoto = AccessHelper.ExecuteNonQuery("update photoinfo set status=" + (int)Status.PhotoStatus.InGrid + " where photoid=" + inPhotoID, oleConn, tran);
                                        if (UpdatePhoto == 0)
                                        {
                                            tran.Rollback();
                                            OutGridName = "";
                                            outGridInfo_Grid = null;
                                            outGridID = 0;
                                            return -2;//照片未打印
                                        }
                                    }
                                    int PhotoStatusInGrid = (int)Status.PhotoStatus.InGrid;
                                    string OtherStatus = "select count(*) from photoinfo where status<>" + PhotoStatusInGrid + " and orderproductid=" + orderproductid;
                                    int otherCount = (int)AccessHelper.ExecuteScalar(OtherStatus, oleConn, tran);
                                    if (otherCount != 0)
                                    {
                                        outGridInfo_Grid = ConvertToView(gridID, orderproductid, oleConn, tran);
                                        outGridID = gridID;
                                        tran.Commit();
                                        return 0; //在格子中，未分片完成
                                    }
                                    else
                                    {
                                        string UpdateGrid = "update grid set OrderID=0,status=" + (int)Status.GridStatus.wait + " where gridid=" + gridID;
                                        int gridUp = AccessHelper.ExecuteNonQuery(UpdateGrid, oleConn, tran);
                                        if (gridUp > 0)
                                        {
                                            string updateOrder = "update orderinfo set status=" + (int)Status.OrderStatus.Complete + " where orderproductid=" + orderproductid;
                                            if (AccessHelper.ExecuteNonQuery(updateOrder, oleConn, tran) > 0)
                                            {
                                                outGridInfo_Grid = ConvertToView(gridID, orderproductid, oleConn, tran);
                                                outGridID = gridID;
                                                tran.Commit();
                                                return 1; //最后一张进格子完成
                                            }
                                            else
                                            {
                                                OutGridName = "";
                                                outGridInfo_Grid = null;
                                                outGridID = 0;
                                                tran.Rollback();
                                                return -4;//数据连接错误
                                            }
                                        }
                                        else
                                        {
                                            OutGridName = "";
                                            outGridInfo_Grid = null;
                                            outGridID = 0;
                                            tran.Rollback();
                                            return -4;//数据连接错误
                                        }
                                    }
                                }
                            }
                            else///产品未占用格子
                            {
                                //检查产品是否完成
                                string QueryOrder = "select status from orderinfo where orderproductid=" + orderproductid;
                                int Orderstatus = (int)AccessHelper.ExecuteScalar(QueryOrder, oleConn, tran);
                                if (Orderstatus == (int)Status.OrderStatus.Complete)
                                {
                                    OutGridName = "";
                                    outGridInfo_Grid = null;
                                    outGridID = 0;
                                    tran.Rollback();
                                    return 2;//产品已经已完成
                                }
                                else
                                {
                                    int GridStatusWait = (int)Status.GridStatus.wait;
                                    string QueryUseFistGrid = "select min(val(Mid(gridName,2,Len(gridName)-1))) as Num from grid  where subareaid=" + inSubAreaID + " and status=" + GridStatusWait;
                                    //DataTable t=AccessHelper.dataTable(QueryUseFistGrid, oleConn, tran);
                                    var gn = Convert.ToInt32(AccessHelper.ExecuteScalar(QueryUseFistGrid, oleConn, tran));
                                    int GridName = Convert.ToInt32(gn == null ? 0 : gn);
                                    if (GridName == 0)
                                    {
                                        OutGridName = "";
                                        outGridInfo_Grid = null;
                                        outGridID = 0;
                                        tran.Rollback();
                                        return -3;//没有可用格子 

                                    }
                                    else
                                    {
                                        string QueryPhotos = "select count(*) from photoinfo where orderproductid=" + orderproductid;
                                        if ((int)AccessHelper.ExecuteScalar(QueryPhotos, oleConn, tran) == 1)
                                        {

                                            string updatephoto = "update  photoinfo set status=" + (int)Status.PhotoStatus.InGrid + " where photoid=" + inPhotoID;
                                            if (AccessHelper.ExecuteNonQuery(updatephoto, oleConn, tran) != 0)
                                            {
                                                string updateOrder = "update orderinfo set status=" + (int)Status.OrderStatus.Complete + " where orderproductid=" + orderproductid;
                                                if (AccessHelper.ExecuteNonQuery(updateOrder, oleConn, tran) != 0)
                                                {
                                                    OutGridName = "A单张";
                                                    outGridInfo_Grid = ConvertToView(0, orderproductid, oleConn, tran);
                                                    outGridID = 0;
                                                    tran.Commit();
                                                    return 3;//单张直接完成不需要分配格子
                                                }
                                                else
                                                {
                                                    OutGridName = "";
                                                    outGridInfo_Grid = null;
                                                    outGridID = 0;
                                                    tran.Rollback();
                                                    return -4;//数据连接错误
                                                }

                                            }
                                            else
                                            {
                                                OutGridName = "";
                                                outGridInfo_Grid = null;
                                                outGridID = 0;
                                                tran.Rollback();
                                                return -4;//数据连接错误
                                            }

                                        }
                                        else//多张第一次进格子
                                        {
                                            string queryGrid = "select * from grid where val(Mid(gridName,2,Len(gridName)-1))=" + GridName + " and SubAreaId=" + inSubAreaID;
                                            DataTable tableNewGrid = AccessHelper.dataTable(queryGrid, oleConn, tran);
                                            OutGridName = (string)tableNewGrid.Rows[0]["gridname"];
                                            int gridid = (int)tableNewGrid.Rows[0]["gridid"];
                                            string updateGrid = "update grid set orderid=" + orderproductid + ",status=" + (int)Status.GridStatus.used + " where gridid=" + gridid;
                                            if (AccessHelper.ExecuteNonQuery(updateGrid, oleConn, tran) > 0)
                                            {
                                                string updatePhoto = "update photoinfo set status=" + (int)Status.PhotoStatus.InGrid + " where photoid= " + inPhotoID;
                                                if (AccessHelper.ExecuteNonQuery(updatePhoto, oleConn, tran) > 0)
                                                {
                                                    outGridInfo_Grid = ConvertToView(gridid, orderproductid, oleConn, tran);
                                                    outGridID = gridid;
                                                    tran.Commit();
                                                    return 4;//多张新分配格子 
                                                }
                                                else
                                                {
                                                    OutGridName = "";
                                                    outGridInfo_Grid = null;
                                                    outGridID = 0;
                                                    tran.Rollback();
                                                    return -4;//数据连接错误
                                                }
                                            }
                                            else
                                            {
                                                OutGridName = "";
                                                outGridInfo_Grid = null;
                                                outGridID = 0;
                                                tran.Rollback();
                                                return -4;//数据连接错误
                                            }

                                        }
                                    }

                                }

                            }

                        }

                    }

                }
            }
            finally
            {
                AccessHelper.CloseMyConnection(oleConn);
            }
        }

        private GridInfo_GridDCT ConvertToView(int gridID, int orderProductid, OleDbConnection conn, OleDbTransaction tran)
        {
            GridInfo_GridDCT gridInfoGrid = new GridInfo_GridDCT();
            if (orderProductid != null && orderProductid != 0)
            {
                string QueryOrderinfo = "select * from orderinfo,papertype,paperface where orderinfo.papertypeid=papertype.papertypeid and paperface.paperfaceid=orderinfo.paperfaceid and orderproductid=" + orderProductid;
                DataTable tableOrder = AccessHelper.dataTable(QueryOrderinfo, conn, tran);
                OrderViewDCT product = new OrderViewDCT() { CompleteTime = Convert.ToDateTime(tableOrder.Rows[0]["CompleteTime"]), OrderName = Convert.ToString(tableOrder.Rows[0]["OrderName"]), OrderPath = Convert.ToString(tableOrder.Rows[0]["OrderPath"]), OrderProductId = Convert.ToInt32(tableOrder.Rows[0]["OrderProductId"]), Priority = Convert.ToInt32(tableOrder.Rows[0]["Priority"]), ProductNum = Convert.ToInt32(tableOrder.Rows[0]["ProductNum"]), Remark = Convert.ToString(tableOrder.Rows[0]["Remark"]), StartTime = Convert.ToDateTime(tableOrder.Rows[0]["StartTime"]), Status = Convert.ToInt32(tableOrder.Rows[0]["Status"]) };
                gridInfoGrid.OrderInfo = product;
                List<PhotoDCT> listPhotoInfo = new List<PhotoDCT>();
                string QueryPhoto = "select * from photoinfo where orderproductid=" + Convert.ToInt32(tableOrder.Rows[0]["OrderProductId"]);
                DataTable tablePhoto = AccessHelper.dataTable(QueryPhoto, conn, tran);
                PhotoDCT info;
                for (int j = 0; j < tablePhoto.Rows.Count; j++)
                {
                    info = new PhotoDCT()
                    {
                        Height = Convert.ToDouble(tablePhoto.Rows[j]["Height"]),
                        Width = Convert.ToDouble(tablePhoto.Rows[j]["Width"]),
                        IsReback = Convert.ToBoolean(tablePhoto.Rows[j]["IsReback"]),
                        OrderProductId = Convert.ToInt32(tableOrder.Rows[0]["OrderProductId"]),
                        PhotoId = Convert.ToInt32(tablePhoto.Rows[j]["PhotoId"]),
                        PhotoName = Convert.ToString(tablePhoto.Rows[j]["PhotoName"]),
                        PicPath = Convert.ToString(tablePhoto.Rows[j]["PicPath"]),
                        PixHeight = Convert.ToInt32(tablePhoto.Rows[j]["PixHeight"]),
                        PixWidth = Convert.ToInt32(tablePhoto.Rows[j]["PixWidth"]),
                        Status = Convert.ToInt32(tablePhoto.Rows[j]["Status"]),
                        PrinterId = Convert.ToInt32(tablePhoto.Rows[j]["PrinterId"])

                    };
                    if (info.Height < info.Width)
                    {
                        info.SizeInch = info.Height + "X" + info.Width;
                        info.SizeCM = info.Height * 2.54 + "X" + info.Width * 2.54;
                    }
                    else
                    {
                        info.SizeInch = info.Width + "X" + info.Height;
                        info.SizeCM = info.Width * 2.54 + "X" + info.Width * 2.54;
                    }
                    info.PaperFace = Convert.ToString(tableOrder.Rows[0]["PaperFaceName"]);
                    info.PaperType = Convert.ToString(tableOrder.Rows[0]["PaperTypeName"]);
                    if (info.PrinterId != 0)
                    {
                        info.PrinterName = (string)AccessHelper.ExecuteScalar("select Pname from printer where printerid=" + info.PrinterId);
                    }
                    listPhotoInfo.Add(info);

                }
                product.PhotoS = listPhotoInfo;
                // Grid_InfoDCT gridInfo = new Grid_InfoDCT() { GridId = (int)GridTable.Rows[i]["GridId"], FirstEnterTime = (DateTime)GridTable.Rows[i]["FirstEnterTime"], GridName = (string)GridTable.Rows[i]["GridName"], OrderID = (int)GridTable.Rows[i]["OrderID"], Status = (int)GridTable.Rows[i]["Status"] };
                //gridInfoGrid.GridBaseInfo = gridInfo;
            }
            else
            {
                gridInfoGrid.OrderInfo = null;
            }

            if (gridID != null && gridID != 0)
            {
                string queryGrid = "select *  from grid  where gridid=" + gridID;
                DataTable GridTable = AccessHelper.dataTable(queryGrid, conn, tran);
                if (GridTable.Rows.Count > 0)
                {
                    Grid_InfoDCT gridInfo = new Grid_InfoDCT() { GridId = (int)GridTable.Rows[0]["GridId"], FirstEnterTime = (DateTime)GridTable.Rows[0]["FirstEnterTime"], GridName = (string)GridTable.Rows[0]["GridName"], OrderID = (int)GridTable.Rows[0]["OrderID"], Status = (int)GridTable.Rows[0]["Status"] };
                    gridInfoGrid.GridBaseInfo = gridInfo;
                }
                else
                {
                    gridInfoGrid.GridBaseInfo = null;
                }

            }
            return gridInfoGrid;
        }
        /// <summary>
        /// 强制打印格子
        /// </summary>
        /// <param name="inGGD"></param>
        /// <returns></returns>
        public int ForcePrintGrid(GridInfo_GridDCT inGGD)
        {
            int rtn = 0;
            OleDbConnection oleConn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleConn.BeginTransaction())
            {
                string checkPhoto = "select count(*) from photoinfo where orderproductid=" + inGGD.OrderInfo.OrderProductId + " and status=" + (int)Status.PhotoStatus.WaitPB;
                if ((int)AccessHelper.ExecuteScalar(checkPhoto, oleConn, tran) > 0)
                {
                    rtn = 1;///有未拼版照片不能强制打印
                    return rtn;
                }
                string updateOrder = "update orderinfo set status=" + (int)Status.OrderStatus.Complete + " where orderproductid=" + inGGD.OrderInfo.OrderProductId;
                if (AccessHelper.ExecuteNonQuery(updateOrder, oleConn, tran) > 0)
                {
                    string updatePhotoStatus = "update photoinfo set status=" + (int)Status.PhotoStatus.InGrid + " where orderproductid=" + inGGD.OrderInfo.OrderProductId;
                    if (AccessHelper.ExecuteNonQuery(updatePhotoStatus, oleConn, tran) > 0)
                    {
                        string UpdateGrid = "update grid set OrderID=0,status=" + (int)Status.GridStatus.wait + ",FirstEnterTime='" + "2000-01-01" + "' where gridid=" + inGGD.GridBaseInfo.GridId;
                        if (AccessHelper.ExecuteNonQuery(UpdateGrid, oleConn, tran) > 0)
                        {
                            rtn = 0;
                            tran.Commit();
                        }
                        else
                        {
                            rtn = -1;
                            tran.Rollback();
                        }

                    }
                    else
                    {
                        rtn = -1;
                        tran.Rollback();
                    }
                }
                else
                {
                    rtn = -1;
                    tran.Rollback();
                }
            }
            AccessHelper.CloseMyConnection(oleConn);
            return rtn;
        }
        /// <summary>
        /// 清空格子
        /// </summary>
        /// <param name="inGrid"></param>
        /// <returns></returns>
        public int ClearSelectedGrid(GridInfo_GridDCT inGGD)
        {
            int rtn = 0;
            OleDbConnection oleConn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = oleConn.BeginTransaction())
            {
                string updateOrder = "update status=" + (int)Status.OrderStatus.Doing + " where orderproductid=" + inGGD.OrderInfo.OrderProductId;
                if (AccessHelper.ExecuteNonQuery(updateOrder, oleConn, tran) > 0)
                {
                    string updatePhotoStatus = "update photoinfo set status=" + (int)Status.PhotoStatus.Printed + " where orderproductid=" + inGGD.OrderInfo.OrderProductId + " and status=" + (int)Status.PhotoStatus.InGrid;
                    if (AccessHelper.ExecuteNonQuery(updatePhotoStatus, oleConn, tran) > 0)
                    {
                        string UpdateGrid = "update grid set OrderID=0,status=" + (int)Status.GridStatus.wait + ",FirstEnterTime='" + "2000-01-01" + "' where gridid=" + inGGD.GridBaseInfo.GridId;
                        if (AccessHelper.ExecuteNonQuery(UpdateGrid, oleConn, tran) > 0)
                        {
                            rtn = 0;
                            tran.Commit();
                        }
                        else
                        {
                            rtn = -1;
                            tran.Rollback();
                        }

                    }
                    else
                    {
                        rtn = -1;
                        tran.Rollback();
                    }
                }
                else
                {
                    rtn = -1;
                    tran.Rollback();
                }
            }
            AccessHelper.CloseMyConnection(oleConn);
            return rtn;
        }
        /// <summary>
        /// 清柜
        /// </summary>
        /// <param name="infoGrids"></param>
        /// <param name="inNum"></param>
        /// <returns></returns>
        public int PriorityPhoto(List<GridInfo_GridDCT> infoGrids, int inNum)
        {
            int intVal = 0;
            OleDbConnection conn = AccessHelper.OpenMyConnection();
            using (OleDbTransaction tran = conn.BeginTransaction())
            {
                foreach (GridInfo_GridDCT grid in infoGrids)
                {
                    //一个格子就是一个产品

                    List<PhotoDCT> photoList =
                        grid.OrderInfo.PhotoS.Where(
                            p =>
                            p.Status != (int)Status.PhotoStatus.Printed &&
                            p.Status != (int)Status.PhotoStatus.InGrid).ToList();
                    if (inNum == 0)
                    {
                        //等于0为不限制
                        string updatePhoto = "update photoinfo set IsClearBox=" + Convert.ToInt32(true) + " where orderproductid=" + grid.OrderInfo.OrderProductId + " and  status<>" + (int)Status.PhotoStatus.Printed + " and status<>" + (int)Status.PhotoStatus.InGrid;
                        if (AccessHelper.ExecuteNonQuery(updatePhoto, conn, tran) > 0)
                        {
                            string updateBoard = "update board set PrintPriority=12 where status<>" + (int)Status.EnumBoardStatus.Printed + " and boardid in (select distinct board.boardid from board,picmakeup where board.boardid=picmakeup.boardid and picmakeup.photoid in (select photoid from photoinfo  where orderproductid=" + grid.OrderInfo.OrderProductId + " and status<>" + (int)Status.PhotoStatus.Printed + " and status<>" + (int)Status.PhotoStatus.InGrid + "))";
                            if (AccessHelper.ExecuteNonQuery(updateBoard, conn, tran) > 0)
                            {
                                intVal = 0;
                            }
                            else
                            {
                                //intVal = -1;
                                //break;
                            }

                        }
                    }
                    else
                    {
                        if (photoList.Count > inNum)
                        {
                            continue;//大于限制条件的不做处理
                        }
                        else
                        {
                            string updatePhoto = "update photoinfo set IsClearBox=" + Convert.ToInt32(true) + " where orderproductid=" + grid.OrderInfo.OrderProductId + " and  status<>" + (int)Status.PhotoStatus.Printed + " and status<>" + (int)Status.PhotoStatus.InGrid;
                            if (AccessHelper.ExecuteNonQuery(updatePhoto, conn, tran) > 0)
                            {
                                string updateBoard = "update board set PrintPriority=12 where status<>" + (int)Status.EnumBoardStatus.Printed + " and boardid in (select distinct boardid from baord,picmakeup where board.baardid=picmakeup.boardid and picmakeup.photoid in (select photoid from photoinfo  where orderproductid=" + grid.OrderInfo.OrderProductId + " and status<>" + (int)Status.PhotoStatus.Printed + " and status<>" + (int)Status.PhotoStatus.InGrid + "))";
                                if (AccessHelper.ExecuteNonQuery(updateBoard, conn, tran) > 0)
                                {
                                    intVal = 0;
                                }
                                else
                                {
                                    //intVal = -1;
                                    //break;
                                }

                            }


                        }
                    }


                }
                if (intVal == 0)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
            }

            AccessHelper.CloseMyConnection(conn);
            return intVal;
        }
        public int CreateInnerReturn(List<InnerReturn_InfoDCT> CurrPhotoList, out Dictionary<int, int> outPhotoDict)
        {
            //List<PaperWasteRecord_info> listRecord = new List<PaperWasteRecord_info>();
            outPhotoDict = new Dictionary<int, int>();
            OleDbConnection conn = AccessHelper.OpenMyConnection();
            int rtnVal = 0;
            using (OleDbTransaction tran = conn.BeginTransaction())
            {
                List<string> userList = new List<string>();
                Dictionary<int, string> WasteTypeList = new Dictionary<int, string>();
                string QueryName = "select * from Users ";
                DataTable tableUser = AccessHelper.dataTable(QueryName);
                for (int i = 0; i < tableUser.Rows.Count; i++)
                {
                    userList.Add(tableUser.Rows[i]["username"].ToString());
                }
                string QueryWasteType = "select * from PaperWasteType ";
                DataTable TableWasteType = AccessHelper.dataTable(QueryWasteType);
                for (int i = 0; i < TableWasteType.Rows.Count; i++)
                {
                    WasteTypeList.Add((int)TableWasteType.Rows[i]["id"], TableWasteType.Rows[i]["PaperOperationTypeName"].ToString());
                }
                foreach (var g in CurrPhotoList.GroupBy(p => p.OrderProductId))
                {
                    foreach (InnerReturn_InfoDCT viewPhoto in g)
                    {
                        if (!userList.Contains(viewPhoto.CreateUserName))
                        {

                            string insertUser = "insert into users (username) values('" + viewPhoto.CreateUserName + "')";
                            if (AccessHelper.ExecuteNonQuery(insertUser, conn, tran) > 0)
                            {
                                userList.Add(viewPhoto.CreateUserName);
                            }
                        }
                        if (!userList.Contains(viewPhoto.ResponseUserName))
                        {
                            string insertUser = "insert into users (username) values('" + viewPhoto.CreateUserName + "')";
                            if (AccessHelper.ExecuteNonQuery(insertUser, conn, tran) > 0)
                            {
                                userList.Add(viewPhoto.CreateUserName);
                            }
                            if (!WasteTypeList.Values.Contains(viewPhoto.Remark))
                            {

                                string insertWasteType = "insert into PaperWasteType (PaperOperationTypeName) values(" + viewPhoto.Remark + ")";
                                if (AccessHelper.ExecuteNonQuery(insertWasteType, conn, tran) > 0)
                                {
                                    string QuerynewWasteType = "select id from PaperWasteType where PaperOperationTypeName=" + viewPhoto.Remark;
                                    WasteTypeList.Add((int)AccessHelper.ExecuteScalar(QuerynewWasteType, conn, tran), viewPhoto.Remark);
                                }
                            }
                            //                string QueryInnerReturn = "select orderinfo.OrderProductId,photoid,width,heigth,picpath,orderName,photoname,photostatus from orderinfo,photoinfo where orderinfo.orderproductid=photoinfo.orderproductid where photoid=" + viewPhoto.PhotoId;
                            //DataTable tablePhoto = AccessHelper.dataTable(QueryInnerReturn);

                            //string insertSql = "insert into InnerReturn(OrderproductID,PhotoId,Width,Heigth,Width,PhotoAreas,PicPath,CreateTime,Remark,ResponMan,CreateMan) values("
                            //    + (int)tablePhoto.Rows[0]["OrderProductId"] + ","
                            //    + (int)tablePhoto.Rows[0]["PhotoId"] + ","
                            //    + (float)tablePhoto.Rows[0]["Width"] + ","
                            //    + (float)tablePhoto.Rows[0]["Height"] + ","
                            //    + (float)tablePhoto.Rows[0]["Width"] * (float)tablePhoto.Rows[0]["Height"] * 2.54 * 2.54 / 10000+","
                            //    + "'"+(string)tablePhoto.Rows[0]["picpath"]+"',"
                            //    +"'"+DateTime.Now+"',"
                            //    +"'"+viewPhoto.Remark+"',"
                            //    +"'"+viewPhoto.ResponseUserName+"',"
                            //    +"'"+viewPhoto.CreateUserName+"')";
                            string insertInnerreturn = "insert into InnerReturn(OrderproductID,PhotoId,Width,Heigth,PhotoAreas,PicPath,CreateTime,Remark,ResponMan,CreateMan) values("
                                + viewPhoto.OrderProductId + ","
                                + viewPhoto.PhotoId + ","
                                + viewPhoto.Width + ","
                                + viewPhoto.Height + ","
                                + viewPhoto.Width * viewPhoto.Height * 2.54 * 2.54 / 10000 + ","
                                + "'" + viewPhoto.PicPath + "',"
                                + "'" + DateTime.Now + "',"
                                + "'" + viewPhoto.Remark + "',"
                                + "'" + viewPhoto.ResponseUserName + "',"
                                + "'" + viewPhoto.CreateUserName + "')";
                            int insertInnerInt = AccessHelper.ExecuteNonQuery(insertInnerreturn, conn, tran);
                            if (insertInnerInt > 0)
                            {
                                DateTime timeNow = DateTime.Now;
                                string QueryPaperid = "select PrintPaperId from board where boardid=(select boardid from picmakeup where photoid=" + viewPhoto.PhotoId + ")";
                                int paperid = (int)AccessHelper.ExecuteScalar(QueryPaperid, conn, tran);
                                string insertPaperWasteRecords = "insert into PaperWasteRecords(PaperWasteTypeId,PrintPaperId,Length,Width,CreateTime,Status,Remark) values("
                                    + WasteTypeList.FirstOrDefault(p => p.Value == viewPhoto.Remark).Key + ","
                                    + insertInnerInt + ","
                                    + viewPhoto.Height * 2.54 / 100 + ","
                                    + viewPhoto.Width * 2.54 / 100 + ","
                                    + "'" + timeNow + "',"
                                    + (int)Status.WasterPaperStatus.unSure + ","
                                    + "'" + viewPhoto.Remark + "')";
                                if (AccessHelper.ExecuteNonQuery(insertPaperWasteRecords, conn, tran) > 0)
                                {
                                    int wId = (int)AccessHelper.ExecuteScalar("select Id from PaperWasteRecords where createtime=#" + timeNow + "#", conn, tran);
                                    outPhotoDict.Add(viewPhoto.PhotoId, wId);
                                    rtnVal = 0;
                                }
                                else
                                {
                                    rtnVal = -1;
                                    goto bc;
                                }

                            }
                            else
                            {
                                rtnVal = -1;
                                goto bc;
                            }
                        }



                    }



                }
            bc:
                if (rtnVal == 0)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
            }

            return rtnVal;
        }

        public int ChangeWaitSureToWaitMake()
        {
            OleDbConnection conn = AccessHelper.OpenMyConnection();
            int rtnVal = 0;
            using (OleDbTransaction tran = conn.BeginTransaction())
            {

                //string unSureBoardSql = "select * from board where  board.status=" + (int)Status.EnumBoardStatus.WaitSure;
                //DataTable tableUnSure = AccessHelper.dataTable(unSureBoardSql, conn, tran);
                //List<List<int>> listResult = new List<List<int>>();
                //List<BoardSureTemp> ListBoard = new List<BoardSureTemp>();
                //for (int i = 0; i < tableUnSure.Rows.Count; i++)
                //{
                //    ListBoard.Add(new BoardSureTemp() { Boardid = Convert.ToInt32(tableUnSure.Rows[i]["BoardId"]), IsUsed = false, Printerid = Convert.ToInt32(tableUnSure.Rows[i]["PrinterId"]), TemplateID = Convert.ToInt32(tableUnSure.Rows[i]["TemplateID"]), CurrLength = Convert.ToDecimal(tableUnSure.Rows[i]["Length"]) });
 
                //}
                //foreach (var pGroup in ListBoard.GroupBy(p => p.Printerid))
                //{
                //    foreach (var TGroup in pGroup.ToList().GroupBy(p => p.TemplateID))
                //    {
                //        string TemplateLengthSql = "select Length from BoardTemplate where ID=" + TGroup.Key;
                //        decimal MaxLength = (decimal)AccessHelper.ExecuteScalar(TemplateLengthSql, conn, tran);
                //        foreach (BoardSureTemp bst in TGroup)
                //        {
                //            if (!bst.IsUsed)
                //            {
                //                decimal matchLength = MaxLength - bst.CurrLength;
                //                BoardSureTemp matchBst=TGroup.Where(p => p.CurrLength <= matchLength&&p.IsUsed==false).OrderByDescending(or => or.CurrLength).FirstOrDefault();
                //                if (matchBst != null)
                //                {
                //                    bst.IsUsed = true;
                //                    List<int> boards = new List<int>();
                //                    boards.Add(bst.Boardid);
                //                    boards.Add(matchBst.Boardid);
                //                    listResult.Add(boards);
                //                    matchBst.IsUsed = true;
                //                }
                //                else
                //                {
                //                    continue;
                //                }
                                
                //            }
                //        }
 
                //    }
                //}
                //foreach (List<int> borads in listResult)//一组一组的组合
                //{
                //    //吧后一个的x值修改后前一个的length值修正
                //    //先修正第一个的长度
                //    //讲第二个的picmakeup中的 X值变成掉

 
                //}
                    try
                    {
                        string MSql = "update board set status=" + (int)Status.EnumBoardStatus.waitProduct + " where status=" + (int)Status.EnumBoardStatus.WaitSure;
                        int rtnQ = AccessHelper.ExecuteNonQuery(MSql, conn, tran);
                        tran.Commit();
                    }
                    catch
                    {
                        rtnVal = -1;
                    }


            }
            return rtnVal;
        }
        /// <summary>
        /// 获取没确认的版
        /// </summary>
        /// <returns></returns>
        public List<DisPalyBoardInfoDCT> GetUnSureBoardInfo()
        {
            OleDbConnection conn = AccessHelper.OpenMyConnection();
            List<DisPalyBoardInfoDCT> rtnList = new List<DisPalyBoardInfoDCT>();
            using (OleDbTransaction tran = conn.BeginTransaction())
            {
                string BoardListUnSureSql = "select * from board where status=" + (int)Status.EnumBoardStatus.WaitSure;
                DataTable BoardTableUnSure = AccessHelper.dataTable(BoardListUnSureSql);
                for (int i = 0; i < BoardTableUnSure.Rows.Count; i++)
                {
                    DisPalyBoardInfoDCT board = new DisPalyBoardInfoDCT();
                    board.BoardID = Convert.ToInt32(BoardTableUnSure.Rows[i]["BoardId"]);
                    board.Length = (decimal)(Convert.ToDouble(BoardTableUnSure.Rows[i]["Length"]) / Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]) * 2.54);
                    board.UserfulNum = (1 - Convert.ToDecimal(BoardTableUnSure.Rows[i]["WasteRate"])) * 100;
                    string QcountPhoto = "select count(*) from PicMakeUp where boardid=" + board.BoardID;
                    board.FactLength=Convert.ToInt32(BoardTableUnSure.Rows[i]["Length"]);
                    board.PhotoNum = (int)AccessHelper.ExecuteScalar(QcountPhoto);
                    board.UseTime = 0;
                    int TemplateID = Convert.ToInt32(BoardTableUnSure.Rows[i]["TemplateID"]);

                    string BoardTemplateSql = "select PrinterId,id,BoardTemplate.PaperFaceid,BoardTemplate.PaperTypeid as PaperTypeid,PaperFaceName,PaperTypeName,TemplateName,Height,Length from BoardTemplate,PaperFace,PaperType where ID=" + TemplateID + " and BoardTemplate.PaperTypeId=PaperType.PaperTypeId and BoardTemplate.PaperFaceId=PaperFace.PaperFaceID";
                    DataTable BoardTemplateTable = AccessHelper.dataTable(BoardTemplateSql);
                    board.BoardTemplate = new BoardTemplate_DCT() { 
                         TemplateId= Convert.ToInt32(BoardTemplateTable.Rows[0]["ID"]),
                         PaperFaceId = Convert.ToInt32(BoardTemplateTable.Rows[0]["PaperFaceId"]),
                         PaperTypeName = BoardTemplateTable.Rows[0]["PaperTypeName"].ToString(),
                         PaperFaceName = BoardTemplateTable.Rows[0]["PaperFaceName"].ToString(),
                         PaperTypeId = Convert.ToInt32(BoardTemplateTable.Rows[0]["PaperTypeId"]),
                         Height = (float)Convert.ToDecimal(BoardTemplateTable.Rows[0]["Height"]),
                         Length = (float)Convert.ToDecimal(BoardTemplateTable.Rows[0]["Length"]),
                         PrinterId = Convert.ToInt32(BoardTemplateTable.Rows[0]["PrinterId"]),
                         TemplateName = BoardTemplateTable.Rows[0]["TemplateName"].ToString()
                          

                          
                          
                    };


                    board.PhotoList = new List<PhotoInfo_PBDCT>();
                    string photoSql = "select photoinfo.PhotoId,photoinfo.PhotoName,PicMakeUp.IsWhirl,PicMakeUp.x,PicMakeUp.y,PicMakeUp.BarCodeStatus,Width,Height,DPI,OrderProductId,PicPath from photoInfo,PicMakeUp where PicMakeUp.photoid=photoinfo.photoid and boardid=" + board.BoardID;
                    DataTable PhotoTableUnSure = AccessHelper.dataTable(photoSql);
                    for (int j = 0; j < PhotoTableUnSure.Rows.Count; j++)
                    {
                        PhotoInfo_PBDCT copyPhoto = new PhotoInfo_PBDCT();
                        copyPhoto.PhotoId = Convert.ToInt32(PhotoTableUnSure.Rows[j]["PhotoId"]);
                        copyPhoto.PhotoName = Convert.ToString(PhotoTableUnSure.Rows[j]["PhotoName"]);
                        copyPhoto.IsWhirl = Convert.ToBoolean(PhotoTableUnSure.Rows[j]["IsWhirl"]);
                        copyPhoto.Location = new Point(Convert.ToInt32(PhotoTableUnSure.Rows[j]["x"]), Convert.ToInt32(PhotoTableUnSure.Rows[j]["y"]));
                        copyPhoto.BarCodeStatus = (SmallERP.COM.Status.PhotoBarCodeStatus)Convert.ToInt32(PhotoTableUnSure.Rows[j]["BarCodeStatus"]);
                        copyPhoto.Photo_Base_Info = new PhotoDCT();
                        copyPhoto.Photo_Base_Info.PhotoId = Convert.ToInt32(PhotoTableUnSure.Rows[j]["PhotoId"]);
                        copyPhoto.Photo_Base_Info.PhotoName = Convert.ToString(PhotoTableUnSure.Rows[j]["PhotoName"]);
                        int height = Convert.ToInt32(Convert.ToDecimal(PhotoTableUnSure.Rows[j]["Height"]) * Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]));
                        int width = Convert.ToInt32(Convert.ToDecimal(PhotoTableUnSure.Rows[j]["Width"]) * Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]));
                        copyPhoto.Photo_Base_Info.PixFactHeigth = height;
                        copyPhoto.Photo_Base_Info.PixFactWidth = width;
                        copyPhoto.Photo_Base_Info.PixHeight = height;
                        copyPhoto.Photo_Base_Info.PixWidth = width;
                        copyPhoto.Photo_Base_Info.Width = Convert.ToDouble(PhotoTableUnSure.Rows[j]["Width"]);
                        copyPhoto.Photo_Base_Info.Height = Convert.ToDouble(PhotoTableUnSure.Rows[j]["Height"]);
                        copyPhoto.Photo_Base_Info.DPI = Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]);
                        copyPhoto.Photo_Base_Info.OrderProductId = Convert.ToInt32(PhotoTableUnSure.Rows[j]["OrderProductId"]);
                        copyPhoto.Photo_Base_Info.PicPath = Convert.ToString(PhotoTableUnSure.Rows[j]["PicPath"]);
                        board.PhotoList.Add(copyPhoto);

                    }
                    rtnList.Add(board);
                }

            }
            return rtnList;
        }

        public List<BoardInfoDCT> GetBoardInfo(string BoardName, DateTime inSTTime, DateTime inEndTime)
        {
            List<BoardInfoDCT> listRtn = new List<BoardInfoDCT>();
            OleDbConnection conn = AccessHelper.OpenMyConnection();

            using (OleDbTransaction tran = conn.BeginTransaction())
            {
                string BoardListUnSureSql = "";
                if (!string.IsNullOrEmpty(BoardName))
                {
                    BoardListUnSureSql = "select * from board where picPath like'%" + BoardName + "%' and createtime <#" + inEndTime + "# and createtime>#" + inSTTime + "#";
                }
                else
                {
                    BoardListUnSureSql = "select * from board where  createtime <#" + inEndTime + "# and createtime>#" + inSTTime + "#";

                }

                DataTable BoardTableUnSure = AccessHelper.dataTable(BoardListUnSureSql);
                for (int i = 0; i < BoardTableUnSure.Rows.Count; i++)
                {
                    BoardInfoDCT board = new BoardInfoDCT();

                    board.Width = (decimal)(Convert.ToDouble(BoardTableUnSure.Rows[i]["Length"]) / Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]) * 2.54);
                    board.Height = (decimal)(Convert.ToDouble(BoardTableUnSure.Rows[i]["Height"]) / Convert.ToInt32(BoardTableUnSure.Rows[i]["DPI"]) * 2.54);
                    board.UsefulNum = (1 - Convert.ToDecimal(BoardTableUnSure.Rows[i]["WasteRate"])) * 100;
                    board.BoardPath = (string)BoardTableUnSure.Rows[i]["picPath"];
                    board.BoardName = board.BoardPath.Substring(0, board.BoardPath.IndexOf("."));

                    string QcountPhoto = "select SUM(Height*Width*2.54*2.54/10000) AS photoSum from PicMakeUp,photoinfo where boardid=" + Convert.ToInt32(BoardTableUnSure.Rows[i]["BoardId"]) + " and photoinfo.PhotoId=PicMakeUp.PhotoId";
                    var rtn = AccessHelper.dataTable(QcountPhoto);
                    if (rtn.Rows.Count == 0)
                    {
                        board.PhotosAreas = 0;
                    }
                    else
                    {
                        if (rtn.Rows[0][0] is DBNull)
                        {
                            board.PhotosAreas = 0;
                        }
                        else
                        {
                            board.PhotosAreas = Convert.ToDecimal(rtn.Rows[0][0]);
                        }
                    }


                    //listRtnboard.UseTime = 0;
                    listRtn.Add(board);

                }
                tran.Commit();
            }

            return listRtn;
        }

        public bool GetIsClearPhoto()
        {
            string getSql = "select SysOrderPath from SysSetting ";
            string result = (string)AccessHelper.ExecuteScalar(getSql);
            if (!string.IsNullOrEmpty(result))
            {
                if (result.Equals("keep"))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }

        }
        #endregion

        #region IOperateDB 成员


        public string GetFileSavepath()
        {
            string path = "";
            string getSql = "select SysOrderPath from SysSetting ";
            string result = (string)AccessHelper.ExecuteScalar(getSql);
            if (!string.IsNullOrEmpty(result))
            {
                if (result.Equals("keep"))
                {
                    path= "0";
                }
                else if (result.Equals("delete"))
                {
                    path = "0";
                }
                else
                {
                    path = result;
                }


            }
            else
            {
                path= "0";
            }
            return path;
        }


        /// <summary>
        /// 根据photoid 获取数据
        /// </summary>
        /// <param name="photoId"></param>
        /// <returns></returns>
        public PhotoInfo_PBDCT GetPhotoInfo(int photoId)
        {
            string photoSql = "select ph.PhotoId,ph.PhotoName,ph.PicPath,ph.OrderProductId,der.OrderName from photoInfo ph ,orderInfo der where ph.OrderProductId=der.OrderProductId and ph.PhotoId=" + photoId;
            DataTable PhotoTableUnSure = AccessHelper.dataTable(photoSql);
            PhotoInfo_PBDCT copyPhoto = new PhotoInfo_PBDCT();
            if (PhotoTableUnSure != null)
            {
                copyPhoto.PhotoId = Convert.ToInt32(PhotoTableUnSure.Rows[0]["PhotoId"]);
                copyPhoto.PhotoName = Convert.ToString(PhotoTableUnSure.Rows[0]["PhotoName"]);
                copyPhoto.OrderProductId = Convert.ToInt32(PhotoTableUnSure.Rows[0]["OrderProductId"]);
                copyPhoto.PicPath = Convert.ToString(PhotoTableUnSure.Rows[0]["PicPath"]);



                copyPhoto.PhotoIds = Convert.ToInt32(PhotoTableUnSure.Rows[0]["PhotoId"]);
                copyPhoto.PhotoNames = Convert.ToString(PhotoTableUnSure.Rows[0]["PhotoName"]);
                copyPhoto.OrderProductIds = Convert.ToInt32(PhotoTableUnSure.Rows[0]["OrderProductId"]);
                copyPhoto.PicPaths = Convert.ToString(PhotoTableUnSure.Rows[0]["PicPath"]);
                copyPhoto.OrderName = Convert.ToString(PhotoTableUnSure.Rows[0]["OrderName"]);
            }
            return copyPhoto;
        }

        #endregion
    }

    #region //help Class
    //public  class BoardSureTemp
    //{
    //   public int Printerid { get; set; }
    //   public int TemplateID { get; set; }
    //   public int Boardid { get; set; }
    //   public bool IsUsed { get; set; }
    //   public decimal CurrLength { get; set; }


    //}
    
    #endregion

}
